0

コード内のデータからフェッチするためのデータベース接続を作成しましたが、このデータベース インスタンスをグローバルに維持し、プロジェクトの他の部分で使用する必要があります。

同じように私を案内してください。

私は以下のコードを持っています

try
    {   
        // load the DB2 Driver
        Class.forName("com.ibm.db2.jcc.DB2Driver");
        // establish a connection to DB2
        Connection db2Conn = DriverManager.getConnection
        (dbUrl,"wcsadm",dbPass);
        // use a statement to gather data from the database
        Statement st = db2Conn.createStatement();
        String myQuery=null;
        String insQuery=null;
        myQuery = "my query"
        // execute the query
        ResultSet resultSet = st.executeQuery(myQuery); 
        // cycle through the resulSet and display what was grabbed
        while (resultSet.next())
        {
        //do something
        }
        resultSet.close();
        st.close();
        db2Conn.close();
    }
4

3 に答える 3

0

すべての接続を静的メソッドに保持し、null の場合は接続オブジェクトを作成し、それ以外の場合は既存の接続オブジェクトを返します。グローバルな最初のオプションを使用する場合は、静的です。

于 2013-10-11T06:25:59.317 に答える
0

a) db 接続プーリングを検討してください。http://commons.apache.org/proper/commons-dbcp/ を参照してください 。b) dbcp を使用する場合は、プロジェクトの一部への接続を提供するシングルトンを作成します。

あなたのプロジェクト (シングル/マルチ ユーザー、Web ベース) について詳しく知らなければ、これ以上のアドバイスをすることは困難です。

public static class SQL {

Connection connection = null;
String connectionUrl = "jdbc:mysql://localhost:3306/bank";
String connectionUser = "admin";
String connectionPassword = "root";


public SQL(){}

public Connection getConnection () {

  if (connection != null) {
    return connection;
  }
  try{

  Class.forName("com.mysql.jdbc.Driver").newInstance();
  connection = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
  return connection; 
 }
  catch(Exception e){
    e.printStackTrace();
}
 return null;   
 }
  }
于 2013-10-11T06:01:08.893 に答える