当前位置:Gxlcms > 数据库问题 > JDBC管理事务

JDBC管理事务

时间:2021-07-01 10:21:17 帮助过:20人阅读

com.fgy.jdbc; import java.sql.*; /** * 转账小案例 */ public class tx { public static void main(String[] args) { Connection conn = null; PreparedStatement pstm1 = null; PreparedStatement pstm2 = null; try { // 1.导入驱动jar包 // 2.注册驱动 Class.forName("com.mysql.jdbc.Driver"); // 3.获取连接 conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "root"); // 开启事务 conn.setAutoCommit(false); // 4.定义SQL语句 // fan给li转账500 String sql1 = "update account set balance = balance - ? where name = ?"; String sql2 = "update account set balance = balance + ? where name = ?"; // 5.获取statement对象 pstm1 = conn.prepareStatement(sql1); pstm2 = conn.prepareStatement(sql2); pstm1.setDouble(1, 500); pstm1.setString(2, "fan"); pstm2.setDouble(1, 500); pstm2.setString(2, "li"); // 6.执行SQL语句 pstm1.executeUpdate(); // 手动制造异常 // int i = 1 / 0; pstm2.executeUpdate(); // 7.处理结果 // .... // 提交事务 conn.commit(); } catch (Exception e) { e.printStackTrace(); try { if (conn != null) conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } } finally { // 8.释放资源 if (pstm1 != null) { try { pstm1.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstm2 != null) { try { pstm1.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }

JDBC管理事务

标签:balance   pac   manage   count   void   HERE   update   jdb   ring   

人气教程排行