import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* 解决自动提交事务问题
* conn.setAutoCommit(false);
* conn.commit();
* conn.rollback();
*/
public class test04 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//将自动提交机制改为手动提交
conn.setAutoCommit(false);
String sql = "update t_act set balance=? where tno=?";
ps = conn.prepareStatement(sql);
ps.setDouble(1,1000);
ps.setInt(2,111);
int count = ps.executeUpdate();
ps.setDouble(1,1000);
ps.setInt(2,222);
count += ps.executeUpdate();
System.out.println(count==2 ? "成功":"失败");
//程序走到这说明没有问题,进行事务提交
conn.commit();
} catch (ClassNotFoundException | SQLException e) {
//事务回滚
if(conn !=null){
try {
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
e.printStackTrace();
}finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
解决JDBC的自动提交事务问题
最新推荐文章于 2023-09-05 15:00:31 发布
该篇博客展示了如何在Java中处理SQL事务,通过设置`conn.setAutoCommit(false)`禁用自动提交,然后手动调用`conn.commit()`提交事务或`conn.rollback()`回滚事务。示例代码中演示了更新操作,并在遇到异常时回滚事务,确保数据一致性。
1308

被折叠的 条评论
为什么被折叠?



