public final class JdbcUtil {
这里写代码片
private static String DRIVER_CLASS = “com.mysql.jdbc.Driver”;
private static String URL=”jdbc:mysql:///bbs”; //bbs 数据库名
private static String USER = “root”; //mysql 账号
private static String PASSWORD = “123456”; mysql 密码
private static ThreadLocal threadLocal = new ThreadLocal<>();
static {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void closeAll(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
if (st != null)
st.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//**清除缓存,释放资源**
public static void closeResultSet(ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeStatement(Statement st) {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeConnection() {
Connection conn = getConnection();
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
threadLocal.remove();
}
}