Java中的事务处理——使用JDBC方式

使用JDBC方式进行事务处理

在JDBC中,打开一个连接对象Connection时,缺省是auto-commit模式,每个SQL语句都被当作一个事务,即每次执行一个语句,都会自动的得到事务确认。为了能将多个SQL语句组合成一个事务,要将auto-commit模式屏蔽掉。在auto-commit模式屏蔽掉之后,如果不调用commit()方法,SQL语句不会得到事务确认。在最近一次commit()方法调用之后的所有SQL会在方法commit()调用时得到确认。

conn.setAutoCommit(false) 开启事务
conn.commit() 提交事务
conn.rollbalck() 回滚事务
String sql="";
int u=0;
Connection con=null;
con=DbConnection.getConnection();
Statement stmt=con.createStatement();
ResultSet rs=null;
PreparedStatement ps=null;
 
try{
     con.setAutoCommit(false);// 更改JDBC事务的默认提交方式
     sql="update tbl_a t set t.name='"+name1+"',t.reason='"+reason+"'  where t.id='"+gh+"'";
     ps=con.prepareStatement(sql);
     u=ps.executeUpdate();
     if (u>0){System.out.println("ok");}
     //其他sql执行语句
     con.commit();//提交JDBC事务
     con.setAutoCommit(true);// 恢复JDBC事务的默认提交方式

}catch (Exception exc) {
   con.rollBack();//回滚JDBC事务
   exc.printStackTrace();
}
原文地址:https://www.cnblogs.com/bellin124/p/13954490.html