--There is a mechanism called a transaction savepoint. --Sample code for use with Java
In the first place, a transaction refers to "a series of processing flow for performing a certain processing". If any of the processes is completed in a series of processes, it is often the case that the processes updated up to that point are rewound and returned to the state before the processes were performed. However, depending on the situation, you may want to return to a certain point where you do not want to return everything. In such a case, you can set a Savepoint and return (roll back) to that point.
Describe the sample code assuming the process of registering the argument name in the list table.
--Get Savepoint between getting Connection and getting PreparedStatement. --Check if the DB does not support Savepoint, and then get the Savepoint object. --When rolling back to the point where you got the Savepoint, pass a Savepoint object like rollback (save). --For DBs that do not support Savepoint, the Savepoint object remains null, so check it when rolling back and if it is null, do a normal rollback.
--The Savepoint class is included in the java.sql package. --It is possible to have multiple Savepoints in one Connection. In that case, you can give each Savepoint a name. (Not implemented in this sample code)
Java
public void regist(String name) throws SQLException{
Connection con = null;
Savepoint save = null;
String sql = null;
PreparedStatement ps = null;
try{
con = this.getConnection();
if(con.getMetaData().supportsSavepoints()){
save = con.setSavepoint();
}
sql = "insert into list (name) values (?)";
ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.executeUpdate();
ps.close()
}catch(SQLException e){
if(save != null){
con.rollback(save);
}
else{
con.rollback();
}
}finally{
if(con!=null){
try{
con.close();
}catch(SQLException e){
}
}
}
}
Recommended Posts