我想知道在按下按钮(键绑定)完成后,我可以关闭数据库连接。
这是我得到的:
public static void main(String[] argv) {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_test14", "root", "password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("Connection to DB Success!");
} else {
System.out.println("Failed to make connection!");
}
System.out.println("\n" + "----------- Database Results ------------" + "\n");
try {
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM first_table";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id_col = rs.getInt("id");
String name = rs.getString("name");
String address = rs.getString("address");
String p = id_col + " " + name + " " + address;
System.out.println(p);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
我是否必须在查询语句后添加close连接?
希望得到一些帮助。
答案 0 :(得分:0)
实际上这取决于您的业务,如果您刚刚完成使用数据库,然后关闭连接,如果不是,请保持连接打开,但关闭Statement
和ResultSet
反对
对于第二个选项,您可能需要创建一个负责连接的类,并在每次要使用DB时使用它。 检查this寻求帮助。
答案 1 :(得分:0)
我在这做什么
call resultset.close just after finishing your execution. rs.close();
finally
{
try
{
if(stmt!=null)
stmt.close();
}
catch (Throwable th)
{}
catch (Throwable th)
{}
try
{
if (connection != null)
connection.close();
}
catch (Throwable th)
{}
}
}