DBUtil
2023-07-09 本文已影响0人
wqjcarnation
package com.neuedu.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
private static final ThreadLocal<Connection> TL = new ThreadLocal<Connection>();
private static final String URL="jdbc:mysql://localhost:3306/people?characterEncoding=utf-8&useSSL=true";
private static final String DRIVER="com.mysql.jdbc.Driver";
private static final String USERNAME="root";
private static final String PASSWORD="root";
// ��ȡConnection
public static Connection getConn() {
Connection con = null;
con = TL.get();
if (con==null) {
con = createConnection();
TL.set(con);
}
return con;
}
// ����һ������
public static void beginTransaction() throws Exception {
getConn().setAutoCommit(false);
}
// �ύһ������
public static void commitTransaction() throws Exception {
getConn().commit();
getConn().setAutoCommit(true);
}
// �ع�һ������
public static void rollbackTransaction() throws Exception {
getConn().rollback();
}
// �رո�����Դ
public static void close(ResultSet rs, PreparedStatement pst) {
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// �رո�����Դ
public static void close(PreparedStatement pst) {
try {
if (pst != null) {
pst.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// �رո�����Դ
public static void close() {
Connection con = TL.get();
try {
if (con != null) {
con.close();
}
//������Ҫ��������������ڴ���������⡣
TL.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static Connection createConnection() {
Connection con = null;
if (con == null) {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
}
return con;
}
}