比如有个银行,当我进行转账的时候,却突然停电了,我的卡显示扣钱,但是转账的卡却没有增加相应的钱,这就需要实现事务了。
连接数据库的工具类:
utils:
package com.qf2002.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* 2020/8/20
* 16:31
* 注册驱动
* 获取连接
* 增删查
* 释放资源
*/
public class DbUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
//创建线程局部变量
private static ThreadLocal<Connection> threadLocal;
static{
//注册驱动
InputStream in = DbUtils.class.getClassLoader().getResourceAsStream("com/qf2002/utils/dbMessage.properties");
Properties properties = new Properties();
try {
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
threadLocal = new ThreadLocal<>();
} catch (IOException e) {
System.out.println("读取失败...");
}finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
System.out.println("驱动注册失败...");
}
}
//得到连接
public static Connection getConnect(){
try {
//判断线程局部变量中是否有连接
Connection conn = threadLocal.get();
if(conn==null){
//如果没有,创造连接
conn = DriverManager.getConnection(url, user, password);
//放到线程局部变量中
threadLocal.set(conn);
}
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//增删改
public static int update(String sql,Object...objects) throws Exception{
Connection conn = getConnect();
PreparedStatement pstat = null;
try {
pstat = conn.prepareStatement(sql);
for(int i=0;i<objects.length;i++){
pstat.setObject(i+1, objects[i]);
}
return pstat.executeUpdate();
}finally {
shutAll(conn,pstat,null);
}
}
//释放资源
public static void shutAll(Connection conn, Statement stat, ResultSet res){
try {
if (res != null) {
res.close();
}
if