3 回答
TA贡献2019条经验 获得超9个赞
使用try-with-resources语句
String user = "user";
String password = "password";
String url = "jdbc:mysql://localhost:3306/database_name";
try (Connection connect = DriverManager.getConnection(url, user, password);
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table;");
) {
while (rs.next()) {
// TODO
}
} catch (Exception e) {
System.out.println(e);
}
TA贡献1839条经验 获得超15个赞
您可以在块中处理此问题,finally以确保在成功和异常情况下都关闭连接。下面分享示例代码,供大家参考。
import java.sql.*;
class MysqlConnectionExample{
public static void main(String args[]){
String jdbcUrl = "jdbc:mysql://localhost:3306/dbName";
String userName = "userName";
String password = "password";
String driverName = "com.mysql.jdbc.Driver";
Connection con= null;
Statement stmt = null;
try{
// Create connection
Class.forName(driverName);
con = DriverManager.getConnection(jdbcUrl, userName, password);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
// Iterate over the results
while(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
}
catch(Exception e){
System.out.println(e);
}
finally{
// Close connection
con.close();
}
}
}
TA贡献1828条经验 获得超3个赞
如果你使用连接傻瓜,我想这会像你的情况。作为其他答案,我建议使用 'connection.close()'; 如果需要的话,最好添加“trasation”范围。
添加回答
举报