工具类封装事务。close 方法里,ThreadLocal 移除 connection。
public class DBUtils {
public static final String URL = "jdbc:mysql://localhost:3306/mydb1?characterEncoding=utf-8";
public static final String USERNAME = "root";
public static final String PASSWORD = "Liu01234";
public static final String DRIVER_CLASS = "com.mysql.cj.jdbc.Driver";
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
public static Connection getConnection() {
Connection connection = threadLocal.get();
System.out.println("connection = " + connection );
if (connection == null) {
try {
Class.forName(DRIVER_CLASS);
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
threadLocal.set(connection);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
public static void close(AutoCloseable ...args) {
for (AutoCloseable c : args) {
if (c != null) {
try {
c.close();
//Connection 从 threadLocal 中移除
if (c instanceof Connection) {
threadLocal.remove();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// 事务设为手动管理
public st