私は実際にJDBC接続プーリングを使用しているかどうかを判断しようとしています。いくつかの調査をした後、実装はほとんど簡単すぎるようです。実際には定期的な接続より簡単なので、私は確認したいと思います。ここで私はJDBC接続プーリングを使用していますか?
は私の接続クラスです:
public class DatabaseConnection {
Connection conn = null;
public Connection getConnection() {
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost:3306/data");
bds.setUsername("USERNAME");
bds.setPassword("PASSWORD");
try{
System.out.println("Attempting Database Connection");
conn = bds.getConnection();
System.out.println("Connected Successfully");
}catch(SQLException e){
System.out.println("Caught SQL Exception: " + e);
}
return conn;
}
public void closeConnection() throws SQLException {
conn.close();
}
}
は、この真の接続プーリングですか?私はそう別のクラスでの接続を使用しています:
//Check data against database.
DatabaseConnection dbConn = new DatabaseConnection();
Connection conn;
ResultSet rs;
PreparedStatement prepStmt;
//Query database and check username/pass against table.
try{
conn = dbConn.getConnection();
String sql = "SELECT * FROM users WHERE username=? AND password=?";
prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, user.getUsername());
prepStmt.setString(2, user.getPassword());
rs = prepStmt.executeQuery();
if(rs.next()){ //Found Match.
do{
out.println("UserName = " + rs.getObject("username") + " Password = " + rs.getObject("password"));
out.println("<br>");
} while(rs.next());
} else {
out.println("Sorry, you are not in my database."); //No Match.
}
dbConn.closeConnection(); //Close db connection.
}catch(SQLException e){
System.out.println("Caught SQL Exception: " + e);
}
うわー、書き直してくれてありがとう。私のような誰かのための完全な助け。 – ryandlf
このソリューションはスレッドセーフなのでしょうか?私はconnection.close()を呼び出す必要がありますか? – swapyonubuntu
@swapyonubuntu:新しいJava7の「try-with-resources」ステートメントでcloseが自動的に実行されるhttps://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – BalusC