gpt4 book ai didi

JAVA JDBC 重用连接

转载 作者:太空狗 更新时间:2023-10-29 22:53:02 25 4
gpt4 key购买 nike

我有一个 Java 程序,我在其中为选择查询执行一些 JDBC。每次调用 testDataBase() 每次都会调用 DBConnection() 是否可取,或者我应该为所有查询重用一个连接。提前致谢。

private  void testDataBase(String query){
Connection con = DBConnection();
Statement st = null;
ResultSet rs = null;

try {
st = con.createStatement();
rs = st.executeQuery(query);
boolean flag = true;
while (rs.next()) {
String resultString = "";
for(int i = 1; i <=rs.getMetaData().getColumnCount();i++){
resultString=resultString+" "+ rs.getString(i);
}
System.out.println(resultString);
}
} catch (SQLException e) {
e.printStackTrace();

} finally {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}



private Connection DBConnection() {
final String method_name = "DBConnection";
Connection conn = null;
try{
Class.forName(driver).newInstance();
conn = java.sql.DriverManager.getConnection(url,userName,password);

}catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}

return conn;
}

最佳答案

就性能而言,打开数据库连接是一项代价高昂的操作。您应该使用连接池在不同请求之间共享连接。

关于JAVA JDBC 重用连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15382913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com