JDBC控制事务
- 使用Connection对象来管理事务
开启事务 :setAutoCommit(boolean autoCommit):调用该方法设置参数为false,即可开启事务
提交事务:commit()
回滚事务: rollback
转账案例
package cn.itcats;
import cn.Utils.JDBCutils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* JDBC控制事务
* 1.使用Connection对象来管理事务
* 开启事务 :setAutoCommit(boolean autoCommit):调用该方法设置参数为false,即可开启事务
* 提交事务:commit()
* 回滚事务: rollback
* 转账案例
*
*/
public class JDBCdemo07 {
public static void main(String[] args) {
Connection conn =null;
PreparedStatement pre1 =null;
PreparedStatement pre2 =null;
try {
conn = JDBCutils.getConnection();
//开启事务
conn.setAutoCommit(false);
String sql1 = "update user set balance =balance + ? where username = ?";
String sql2 = "update user set balance =balance - ? where username = ?";
//获取执行对象
pre1 = conn.prepareStatement(sql1);
pre2 = conn.prepareStatement(sql2);
pre1.setInt(1,500);
pre1.setString(2,"佩奇");
pre1.setInt(1,500);
pre1.setString(2,"乔恩");
//执行
int i = pre1.executeUpdate();
pre2.executeUpdate();
System.out.println(i);
//提交事务
conn.commit();
} catch (Exception e) {
//事务回滚
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}finally{
JDBCutils.close(pre1,conn);
try {
pre2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}