2020年10月19日:
工具类其二:
连接数据库的工具类:
package shujuku;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class shuju {
private static ThreadLocal<Connection> conns=new ThreadLocal<Connection>();
public static Connection getConnection()
{
Connection conn=conns.get();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e1){
e1.printStackTrace();
}
if(conn==null){
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/kecheng?serverTimezone=UTC","root","150023");
conns.set(conn);
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
return conn;
}
public static void close(Connection connection)
{
try {
if (connection != null)
{
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void commitAndclose() {
Connection connection=conns.get();
if(connection!=null) {
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
conns.remove();
}
public static void rollbackAndclose() {
Connection connection=conns.get();
if(connection!=null) {
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
conns.remove();
}
}
此段代码适用于自己今后写项目时共用的数据库连接代码,这样一来,以后写数据库就调用这个方法就能实现数据库的连接,很是方便。