一、JDBC实现事务管理
try {
set autocommit=0; //在事务结束之前的所有DML处于同一个事务中
update account set money=money-100 where card_id='1234567890';
update account set money=moy-100 where card_id='0515151515'
commit; //提交事务
}catch() {
rollback;
}
首先开启事务,然后执行DML操作,如果所有的DML操作都正确执行,则使用commit提交事务;如果有的DML操作不能正确执行,则捕获该异常,跳过commit语句,在catch语句块中使用rollback回滚事务。
二、使用JDBC实现事务处理
public class Test {
public static void main(String[] args) {
Statement statement =null;
Connection connection=null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
connection.setAutoCommit(false);//相当于 set autocommit=0;
statement =connection.createStatement();
statement.addBatch("update account set money=money-100 where card_id= '1234567890'");
statement.addBatch("update account set money=money+100 where card_id= '0987654321'");
statement.executeBatch();
connection.commit();
} catch (Exception e) {
try {
//如果不对connection进行判断,若连接数据库操作过程出错,就会产生空指针异常。
if(connection!=null) {
connection.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
if (statement!=null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
执行过程分析:
1、connection.setAutoCommit(false);相当于set autocommit=0;即先设置自动提交功能为禁用。
2、statement =connection.createStatement();创建语句
3、调用addBacth方法,将sql语句添加到Statement对象中。
4、调用executeBatch方法,批量处理Statement对象中的sql语句。
5、如果sql语句全部能够正确执行,则调用commit()方法提交事务;如果sql中有的语句不能正确执行,则捕获该异常,跳过connection.commit()语句,在catch语句块中调用rollback()方法回滚事务。