先创建一个properties文件
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/xxxx
username = root
password = xxxx
创建一个类
public class DBUtils{
private static final Properties PROPERTIES = new Properties();//存储配置文件的map
private static final ThreadLocal THREAD_LOCAL = new ThreadLocal<>();
static {
InputStream is = DBUtils.class.getResourceAsStream("/xxxx.properties");
try{
PROPERTIES.load(is);
Class.forName(PROPERTIES.getProperty("driver"));
} catch (IOException e) {
e.peintStackTrace();
} catch (ClassNotFoundException e) {
e.peintStackTrace();
}
}
public static Connection getConnection(){
Connection connection = THREAD_LOCAL.get();
try{
if(connection == null){
connection = DriverManager.getConnection(PROPERTIES.getProperty("url"),PROPERTIES.getProperty("username"),PROPERTIES.getProperty("password"));
THREAD_LOCAL.set(connection);
}
} catch (SQLException e) {
e.peintStackTrace();
}
return connection ;
}
//开启事务
public static void begin(){
Connection connection = null;
try{
connecction = getConnection();
connection.setAutoCommit(false);
} catch (SQLException e) {
e.peintStackTrace();
}
}
//提交事务
public static void commit(){
Connection connection = null;
try{
connecction = getConnection();
connection.commit();
} catch (SQLException e) {
e.peintStackTrace();
}
}
//回滚事务
public static void rollback(){
Connection connection = null;
try{
connecction = getConnection();
connection.rollback();
} catch (SQLException e) {
e.peintStackTrace();
}
}
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
try {
if(resultSet != null)
resultSet.close();
if(statement != null)
statement.close();
if(connection != null){
connection.close();
THREAD_LOCAL.remove();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
***用的时候把代码中的xxxx替换就可以啦!!***!