package demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.dbutils.QueryRunner;
import utils.C3P0Utils;
public class Test {
public static void main(String[] args) {
dbutilsTransaction();
}
/*
* 功能同jdbcTransaction
*/
public static void dbutilsTransaction() {
//为了确保开启与执行的都是同一个conn链接需要单独获得此链接,在update中传入conn
Connection conn = C3P0Utils.getConnection();
QueryRunner qr = new QueryRunner();
try {
conn.setAutoCommit(false);
String sql = "update account set money=money-500 where name='alex'";
String sql1 = "update account set money=money+500 where name='alex1'";
qr.update(conn, sql);
int i = 1/0;
qr.update(conn, sql1);
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
conn.commit();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void jdbcTransaction() {
Connection conn = null;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获得connection
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/stdb", "root", "Aa123456");
//关闭自动提交(开启事务)
conn.setAutoCommit(false);
//开启事务保证事务内所有sql都执行成功,否则rollback
Statement statement = conn.createStatement();
String sql = "update account set money=money-500 where name='alex'";
String sql1 = "update account set money=money+500 where name='alex1'";
statement.executeUpdate(sql);
//模拟发生错误
int i = 1/0;
statement.executeUpdate(sql1);
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
//事务是需要提交来结束的,不管有没有更改都可以在finally中提交
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
JDBC与DBUtils开启事务代码示例
最新推荐文章于 2022-04-30 14:56:34 发布