package JDBC;
import util.JDBCutil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Demo {
public static void main(String[] args) {
Connection conn = null;
try {
conn = JDBCutil.connection();
//开启事务
conn.setAutoCommit(false);
//给钱
String sql01 = "update account set balance = balance - ? where name = ?";
//收钱
String sql02 = "update account set balance = balance + ? where name = ?";
PreparedStatement pstmt01 = conn.prepareStatement(sql01);
PreparedStatement pstmt02 = conn.prepareStatement(sql02);
pstmt01.setInt(1, 500);
pstmt01.setString(2, "zhangsan");
pstmt02.setInt(1, 500);
pstmt02.setString(2, "wangwu");
int a = pstmt01.executeUpdate();
int b = pstmt02.executeUpdate();
System.out.println(a);
System.out.println(b);
//提交事务
conn.commit();
JDBCutil.close(pstmt01, conn);
JDBCutil.close(pstmt02, null);
} catch (Exception e) {//将异常的范围设置最大,一旦发生任何异常,都会回滚
//一旦发生异常就回滚
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
}
}
}
JAVA单排日记-2020/3/15-JDBC-事务
最新推荐文章于 2020-03-15 19:57:26 发布