In database operations, a transaction is an indivisible unit of work that consists of one or more SQL statements that are updated on the database. The entire transaction can be committed to the database only if all operations in the transaction are completed properly, and the entire transaction must be undone if an operation is not completed. We end the transaction by committing a commit () or rolling back rollback (). The methods for transaction operations are all in the interface java.sql.Connection.
When you first establish a connection to a database, by default, the connection is in autocommit mode, and in the JDBC API, you can suppress autocommit transactions by calling Setautocommit (false). You can then make a multiple update database SQL statement as a transaction, after all operations are completed, invoke commit () to commit the whole. If one of the SQL operations fails, the commit () method is not executed and the corresponding SqlException is generated, in which case the rollback () method is invoked to undo the transaction by capturing the exception code block. Here is an example;
For example: There are two tables, a record user account (UserAccount), one is the System account (Sysaccount), now has a user to send money to the system to buy things, will be the following two statements:
String sql1 = "update useraccount set monery=monery-1000 where name='username'";
String sql2 = "update sysaccount set monery=monery+1000 where name='sysname'";
But if the first one executes and the second statement executes wrong, it can cause undesirable consequences. This is the way to prevent this from happening by manually submitting: the main code
try{
.
.
.
conn=DriverManager.getConnection("..."); //链接数据库
conn.setAutoCommit(false);//禁止自动提交事务
stmt = conn.Create....
String sql1 = "update useraccount set monery=monery-1000 where name='usename'";
String sql2 = "update sysaccount set monery=monery+1000 where name='sysname'";
stmt=conn.createStatement();
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
conn.commit(); //统一提交。
}catch(SQLException e){
conn.rollback(); //倘若其中一项sql操作失败,就不会执行commit()方法,而是产生相应的sqlexception,此时就可以捕获 异常代码块中调用rollback()方法撤消事务。
e.printStackTrace();
}
finally{
if(stmt!=null){
stmt.close();
}
if(conn!=null){
stmt.close();
}
}