下面用简单的实例演示一下什么是批处理操作
Statement和PreparedStatement提供例了批处理与事务操作,用来一次执行多条语句。下面用Statement操作。
Statement接口提供批处理方法:
- 添加批处理数据public void addBatch(String sql)throws SQLException
- 执行批处理数据 public int[] executeBatch()throws SQLException
注:返回的是int数组,每个数据依次为每条sql影响的行数.
Connection中提供操作事务的方法:
- 提交事务 public void commit()throws SQLException
- 撤销事务public void rollback()throws SQLException
- 是否为自动提交public void setAutoCommit(boolean autoCommit)throws SQLException
注:该方法参数默认为true,为false时程序会将一组SQL作为一个事务调用commit()执行提交。
观察如下代码:
package com.dao.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Arrays;
public class Test2 {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/school";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
try {
Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = connection.createStatement();
stmt.addBatch("insert into grade(grade_id,grade_name) VALUES(9,'10');");
stmt.addBatch("insert into grade(grade_id,grade_name) VALUES(10,'12');");
stmt.addBatch("insert into grade(grade_id,grade_name) ***VALUES(11,'13');");
stmt.addBatch("insert into grade(grade_id,grade_name) VALUES(12,'14');");
int len[] = stmt.executeBatch();
System.out.println(Arrays.toString(len));
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
在以上程序中第三条SQL出现错误,但是查询数据库发现前两条数据插入成功,这不符合事务操作,作如下修改,将事务自动提交设为false,如果没有出现错误,调用commit提交事务,否则调用rollback进行事务回滚,将已经执行成功的数据再删除。
package com.dao.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Arrays;
public class Test2 {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/school";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static void main(String[] args) throws Exception {
Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
connection.setAutoCommit(false);
Statement stmt = connection.createStatement();
try {
stmt.addBatch("insert into grade(grade_id,grade_name) VALUES(9,'10');");
stmt.addBatch("insert into grade(grade_id,grade_name) VALUES(10,'12');");
stmt.addBatch("insert into grade(grade_id,grade_name) VALUES(11,'13');");
stmt.addBatch("insert into grade(grade_id,grade_name) VALUES(12,'14');");
int len[] = stmt.executeBatch();
System.out.println(Arrays.toString(len));
connection.commit();
connection.close();
} catch (Exception e) {
e.printStackTrace();
connection.rollback();
}
}
}
以上为手工处理事务,在开发中由容器帮我们自动完成。