我有一个Java程序,我在其中为选择查询做一些JDBC.每次inturns调用DBConnection()时我都应该调用testDataBase(),或者我应该为所有查询重用一个连接.提前致谢.
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;
}
Run Code Online (Sandbox Code Playgroud)
获取数据库连接是一项非常昂贵的操作,因此建议尽可能重用连接。还可以考虑使用连接池,它将为您维护许多连接,因此您可以在需要时从池中获取一个。上面显示的方法可能不需要更改,这取决于您调用的 DBConnection() 方法。
| 归档时间: |
|
| 查看次数: |
10825 次 |
| 最近记录: |