描述
Java 1.7中新增的try-with-resource语法可以用来自动关闭打开的资源,如流、数据库连接、Socket连接等,这可以减少代码量,避免忘记关闭资源导致的资源泄露等问题
关闭jdbc连接的传统写法
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8", "root", "123456");
stmt = con.createStatement();
String sql = "insert into students values(1," + "'小明'" + "," + 男+ "," + 12+ ")";
stmt .execute(sql);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 先关闭Statement
if (stmt != null)
try {
stmt .close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 后关闭Connection
if (con != null)
try {
con .close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
使用try-with-resource关闭jdbc连接
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try (
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF-8", "root", "123456");
Statement stmt = con.createStatement();
)
{
String sql = "insert into hero values(1," + "'小明'" + "," + 男 + "," + 12 + ")";
stmt.execute(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
实现了AutoCloseable接口的类可以使用try-with-resource自动关闭连接,如Connection和Statement。
用法:在try-catch的try后的()中创建连接,后续不需要手动关闭
try (
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
Statement stmt = c.createStatement(); )
{
//代码块
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
参考文章
https://blog.csdn.net/weixin_43834780/article/details/104376956