5

まず、タイトルの名前で申し訳ありませんが、英語は私の母国語ではないため、別の名前を付ける方法がわかりません.

データベースに接続するには、次の方法があります。

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class PgConnect {
    public  void connect() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return;
        }
        if (connection != null) {
            System.out.println("Connection working");
        } else {
            System.out.println("Failed to make connection!");
        }
    }
}

そして、私がする必要があるのは、PgConnect以下のコードに のメソッドを含めることです。データベースへのSQLの呼び出しには多くの種類があるため、基本的にこれが必要です。これをそのように変更すると、資格情報/ホストが1つのファイルにのみあるため、保守が簡単になります。

コメントがあるところに変更を加える必要があると思います

// i want to change this, for using the method on the first file. 

私が間違っている場合は、私を修正してください。

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ReturnResults {

    public static void main(String[] args) {
        Connection connection = null;
        try {
                // i want to change this, for using the method on the first file.
            connection = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");

        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return;
        }
        if (connection != null) {

            String result = null;
            String selectString = "select * from mwp.servers where env='TEST' order by server";
            //result ="iServer\tLabel\n";

            try {

                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery(selectString);

                while (rs.next()) {

                    String iEnv     = rs.getString("env");
                    String iServer  = rs.getString("iserver");
                    String iLabel   = rs.getString("label");
                    String iTitle   = rs.getString("title");
                    String iLogin   = rs.getString("login");

                    result=iEnv+"\t"+ iServer+"\t"+iLabel+"\t"+iTitle+"\t"+iLogin;

                    System.out.println(result);
                }
                stmt.close();
                connection.close();

            } catch(SQLException ex) {
                System.err.println("SQLException: " + ex.getMessage());
            }

        } else {
            System.out.println("Failed to make connection!");
        }
    }
}

Perl でこれを行う方法は知っていますが、Java での経験はありません。

4

5 に答える 5

3

メソッドを作成connect()するstaticと、次のように呼び出すことができます

Connection con = PgConnect.connect();

notConnectionを返す必要があるため、メソッド connect to も編集します。Connectionvoid

public static Connection connect() throws SQLException {
    try {
        Connection con = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
        // ...
        return con;
    } 
    catch (SQLException e) {
        e.printStackTrace();
        return null;
    }

また、別のよりクリーンなアプローチもあります。これは私の古いプロジェクトの例です。

private static DataSource getOracleDBConnection() throws NamingException {
        Context c = new InitialContext();
        return (DataSource) c.lookup("java:comp/env/OracleDBConnection");
    }

    public static Connection getOracleDatabaseConnection() {

        Connection conn = null;
        try {
            conn = OracleDAOFactory.getOracleDBConnection().getConnection();
        } 
        catch (NamingException ex) {
            Logger.getLogger(OracleDAOFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
         catch (SQLException ex) {
            Logger.getLogger(OracleDAOFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
        return conn;
    }

私は使用してNetBeansいるので、他の IDE でこれを行う方法はわかりませんが、押すと小さなメニューが表示され、[データベースを使用...ALT+Insert ] を選択して、数回クリックするだけで自動作成できます。あなたのデータベースに。Connection

于 2012-06-20T17:46:12.153 に答える
3

資格情報を非表示にする 1 つの方法は、次のように をconnect返す静的関数を作成することです。Connection

public class PgConnect {
    public static Connection connect() throws SQLException {
    try {
        Connection res = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
        if (res != null) {
            System.out.println("Connection working");
        } else {
            System.out.println("Failed to make connection!");
        }
        return res;
    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        throw e;
    }
}

}

次に、次のように使用できます。

try {
    connection = PgConnect.connect();
} catch (SQLException e) {
    System.out.println("Connection Failed! Check output console");
    e.printStackTrace();
    return;
}
于 2012-06-20T17:46:27.410 に答える
1

void接続を返す代わりに、上記で指定したメソッドを使用できます。

public class PgConnect {
    //changing the method declaration to return a Connection
    public Connection connect() {
        Connection connection = null;
        try {
            connection = DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", "test","test123");
        } catch (SQLException e) {
            System.out.println("Connection Failed! Check output console");
            e.printStackTrace();
            return null;
        }
        if (connection != null) {
            System.out.println("Connection working");
        } else {
            System.out.println("Failed to make connection!");
        }
        return connection;
    }
}



public class ReturnResults {

    public static void main(String[] args) {
        Connection connection = null;
        PgConnect oPgConnect;
        try {
        //this is where you call your method object...
        oPgConnect = new PgConnect();
        //once created, you call the method to get the connection...
        connection = oPgConnect.connect();
        //after get the connection, keep with the method logic...
        if (connection != null) {
            //your logic code...
        }
    }
}
于 2012-06-20T17:48:11.607 に答える
1

私が理解しているように、オブジェクトを使用できるようにからconnect()メソッドを呼び出す必要があります。PgConnect.javaReturnResults.javaConnection

あなたは2つのことをすることができます -

  1. PgConnect.javain ReturnResults.javalikeを拡張してから、メソッドpublic class ReturnResults extends PgConnectを使用できます。connect
  2. クラスを静的にして、クラスのPgConnectように使用できます。PgConnect.connect()ReturnResults
于 2012-06-20T17:50:04.540 に答える
0

SQL呼び出しを行う必要があるたびにそれを呼び出すことができるように、接続を独自の関数に引き出したいと言っていますか? それがあなたが求めていることのようです。私が基地から外れていたらごめんなさい....

しかし、それがあなたが求めているものである場合、これは標準的なことであるため、正しい方向に進んでいます...

これを試してみませんか。答えを提供するだけでなく、作業を開始して生活を楽にするためのベスト プラクティスを設定しようとしました。.... (PGConnect.java が同じパッケージにあると仮定します。アドレスを適切に解決しない場合。SO に関する他の多くの投稿でそれが説明されます。Java/ほとんどのプログラミング言語の基本的なことです。) 最初のファイルを更新します。このように表示するには、Connection を静的にする関数を作成し、呼び出し元のメソッドに例外を渡していることに注意してください。これは、これらの例外をケースバイケースで処理できるようにするためです。アプリケーションで適切なエラー報告ができるように、それらをデータ層から完全に渡すことさえ好みますが、それはアプリケーションの設計方法に大きく依存します。

package DatabaseCodePackage; //name you package something descriptive, its your call place both files into this package.

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class PgConnect {

    public static Connection getConnection(String username, String password) throws SQLException
    {
        return DriverManager.getConnection("jdbc:postgresql://pgserver:5432/db", username, password);
    }

2 番目のファイルを次のように更新します.... 動的検索値を使用している場合、SQL を JDBC に直接入力することはお勧めしません。http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html使用された準備済みステートメントを参照してください。準備済みステートメントを使用するように SQL を書き直しました。

package DatabaseCodePackage; //name you package something descriptive, its your call place both files into this package. 

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class ReturnResults {

public static void main(String[] args) {

     Stirng result = null; 
     try{
         result = selectAllWithEnv("TEST");

      // I catch exceptions here because i like to let exception pass entirely out of the
      // data layer, this way the control logic calling for the database information can decide what to do when it 
      // cant get the information it wants. This is especailly good in a MVC type project. 
    } catch (NullPointerException npe){
        result = "Connection Failed! Check output console : " + e.getMessage();
        e.printStackTrace();
        return;
    } catch (SQLException e) {
        result = "SQL failure! Check output console : " + e.getMessage();
        e.printStackTrace();
        return;
    } finally { 
        System.out.println(result); 
    }
}

public static String selectAllWithEnv(String var) throws SQLException, NullPointerException {
    String SQL = "select * from mwp.servers where env=? order by server";
    Connection connection = null;
    StringBuilder sb = new StringBuiler();
    try {
        connection = PgConnect.getConnection();
        PreparedStatement ps = connection.prepareStatement(SQL);
        ps.setObject(1, var);
        ResuletSet rs = ps.executeQuery();

        while (rs.next()) {

            String iEnv     = rs.getString("env");
            String iServer  = rs.getString("iserver");
            String iLabel   = rs.getString("label");
            String iTitle   = rs.getString("title");
            String iLogin   = rs.getString("login");

            sb.append(iEnv + "\t" + iServer + "\t" + iLabel + "\t" + iTitle + "\t" + iLogin + "\n");
         }
    } finally {
        connection.close();
    }
    return sb.toString();
}

con.close()また、finally ブロックに を入れていることにも注意してください。常に常に常にこれを行います。try ブロックで例外をスローすることになった場合、これにより確実に呼び出されます。これを行わないと、接続が非常に長い時間維持され、パフォーマンスに非常に悪影響を及ぼす可能性があります。エンタープライズ環境で作業していて、これを行わない場合、アプリケーション接続を強制終了しないように、ある時点で DBA に訴えられる可能性があります。同じ接続で複数のステートメントを使用していない場合、 は冗長であるため、呼び出すときにそれを呼び出す理由はありませんstmt.close()con.close()con.close()

于 2012-06-20T18:26:14.867 に答える