用jdbc管理简单的事务,该代码已经用自己定义的工具类简化了
package hj.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* jdbc管理事务
*/
public class day5 {
public static void main(String[] args) {
Connection getconnection=null;
PreparedStatement preparedStatement =null;
PreparedStatement preparedStatement1=null;
try {
getconnection = jdbcutils.getconnection();
getconnection.setAutoCommit(false);
//在执行sql语句之前开启事务
String sql="update dd set id=id-? where name=?";
String sql1="update dd set id=id+? where name=?";
preparedStatement = getconnection.prepareStatement(sql);
preparedStatement1 = getconnection.prepareStatement(sql1);
preparedStatement.setInt(1,134);
preparedStatement.setString(2,"张三");
preparedStatement1.setInt(1,13);
preparedStatement1.setString(2,"l李四");
preparedStatement.executeUpdate();
preparedStatement1.executeUpdate();
getconnection.commit();//执行完所有sql语句后提交事务
} catch (Exception e) {
try {if (getconnection!=null)
getconnection.rollback();//在出现异常时回滚事务
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}finally {
jdbcutils.close3(preparedStatement,getconnection);
jdbcutils.close3(preparedStatement1,null);
}
}
}