目录
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缓存区
2、JDBC获取自增长值
/** * 获取自增长值 * @author APPle */ 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)插入部门 */ //预编译部门sql //stmt = conn.prepareStatement(deptSql); // /** * 1.1 使用两个参数的prepareStatement()方法,指定可以返回自动增长的键值 * Statement.RETURN_GENERATED_KEYS: 可以返回自动增长值 * Statement.NO_GENERATED_KEYS: 不能返回自动增长值 */ stmt = conn.prepareStatement(deptSql, Statement.RETURN_GENERATED_KEYS); //设置参数 stmt.setString(1, "秘书部"); //执行部门sql stmt.executeUpdate(); /** * 1.2 获取自增长的值 */ rs = stmt.getGeneratedKeys(); Integer deptId = null; if(rs.next()){ deptId = rs.getInt(1);//得到第一行第一列的值 }
/** * 2)插入员工,员工在刚添加的部门中 */ stmt = conn.prepareStatement(empSql); //设置参数 stmt.setString(1, "李四"); stmt.setInt(2, deptId); //如何获取刚刚添加的部门ID?? //执行员工sql stmt.executeUpdate();
}catch(Exception e){ e.printStackTrace(); } |