1 JDBC进行批处理
1.1 为什么要用批处理?
之前:一次操作只能发送一条sql语句到数据库服务器,效率并不高!
如果要插入2000条记录,那么必须发送2000条sql语句。
如果IO流的话,一次写出一个字节,显然效率效率并不高,所以可以使用缓存字节数组提高每 次写出的效率。
现在:插入2000条记录,但现在使用sql缓存区,一次发送多条sql到数据库服务器执行。这种做法就叫做批处理。
1.2 JDBC批处理的API
Statement批处理:
void addBatch(String sql) 添加sql到缓存区(暂时不发送)
int[] executeBatch() 执行批处理命令。 发送所有缓存区的sql
void clearBatch() 清空sql缓存区
PreparedStatement批处理:
void addBatch() 添加参数到缓存区
int[] executeBatch() 执行批处理命令。 发送所有缓存区的sql
void clearBatch() 清空sql缓存区
![这里写图片描述](https://i-blog.csdnimg.cn/blog_migrate/75b5cda71441da87b3778e8f66099843.png)
2 JDBC获取自增长值
/**
* 获取自增长值
*/
public class Demo1 {
@Test
public void test(){
String deptSql = "INSERT INTO dept(deptName) VALUES(?)";
String empSql = "INSERT INTO employee(empName,deptId) VALUES(?,?)";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try{
conn = JdbcUtil.getConnection();
/**
* 1)插入部门
*/
/**
* 1.1 使用两个参数的prepareStatement()方法,指定可以返回自动增长的键值
* Statement.RETURN_GENERATED_KEYS: 可以返回自动增长值
* Statement.NO_GENERATED_KEYS: 不能返回自动增长值
*/
stmt = conn.prepareStatement(deptSql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, "秘书部");
stmt.executeUpdate();
/**
* 1.2 获取自增长的值
*/
rs = stmt.getGeneratedKeys();
Integer deptId = null;
if(rs.next()){
deptId = rs.getInt(1);
}
/**