import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Test;
import com.atguigu.util.JDBCUtil;
public class TransactionTest {
@Test
public void updateTest() {
Connection conn = null;
try {
//连接数据库
conn = JDBCUtil.getConnection();
//把自动提交给关闭
conn.setAutoCommit(false);
String sql1 = "update user_table set balance = balance - 100 where user = ?";
update(conn, sql1, "AA");
String sql2 = "update user_table set balance = balance + 100 where user = ?";
update(conn, sql2, "BB");
//模拟异常操作
// System.out.println(10/0);
//提交事务
conn.commit();
} catch (Exception e) {
e.printStackTrace();
try {
//如果出现异常则回滚
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally {
try {
//将自动提交给开启,在归还给数据连接池。
conn.setAutoCommit(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//关闭连接
JDBCUtil.closeResourse(conn, null);
}
}
public void update(Connection conn,String sql,Object... agrs) throws Exception {
//预编译sql语句,得到preparedstatement对象
PreparedStatement ps = conn.prepareStatement(sql);
//填充占位符
for(int i = 0;i <agrs.length;i++) {
ps.setObject(i+1, agrs[i]);
}
//执行preparedstatement
ps.execute();
//关闭资源,但不关闭连接
JDBCUtil.closeResourse(null, ps);
};
}
JDBC-事务的处理
最新推荐文章于 2024-11-04 20:33:37 发布