网络上有许多的关于jdbc的工具类,下面的代码是我自己整理的一个完整的Jdbc工具类,方便于以后的项目工作。
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();
}
}