在与数据库操作时,如果执行多条更新的SQL语句(如:update或insert语句),在执行第一条后如果出现异常或电脑断电,
则后面的SQL语句执行不了,这时候设定我们自己提交SQL语句,不让JDBC自动提交,格式为:
conn.setAutoCommit(false);
执行多条SQL语句;
conn.commit();
//恢复自动提交模式
conn.setAutoCommit(true);
代码示例:
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- public class TestTransaction {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Connection con = null;
- Statement stmt = null;
- ResultSet rs = null;
- PreparedStatement ps = null;
- try {
- Class.forName("com.mysql.jdbc.Driver");
- con = DriverManager.getConnection(
- "jdbc:mysql://localhost:3306/mydb", "root", "root");
- System.out.println("连接数据库成功!");
- stmt = con.createStatement();
- // JAVA默认为TRUE,我们自己处理需要设置为FALSE,并且修改为手动提交,才可以调用rollback()函数
- con.setAutoCommit(false);
- stmt.addBatch("insert into people values(078,'ding','duo')");
- stmt.addBatch("insert into people values(30,'nokia','ddd')");
- stmt.executeBatch();
- // 事务提交
- con.commit();
- // 设置为自动提交,改为TRUE
- con.setAutoCommit(true);
- /*
- * String sql = "select * from people"; rs = stmt.executeQuery(sql);
- * while(rs.next()){ System.out.println(rs.getString("id") + " " +
- * rs.getString("name")); }
- */
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException se) {
- se.printStackTrace();
- try {
- // 产生的任何SQL异常都需要进行回滚,并设置为系统默认的提交方式,即为TRUE
- if (con != null) {
- con.rollback();
- con.setAutoCommit(true);
- }
- } catch (SQLException se1) {
- se.printStackTrace();
- }
- } finally {
- try {
- if (rs != null) {
- rs.close();
- rs = null;
- }
- if (stmt != null) {
- stmt.close();
- stmt = null;
- }
- if (con != null) {
- con.close();
- con = null;
- }
- } catch (SQLException se) {
- se.printStackTrace();
- }
- }
- }
- }