黑马day10 批处理Statement&PrepareStatement处理方式对比

来源:互联网 发布:rsa算法c语言实现 编辑:程序博客网 时间:2024/06/04 01:28

1.Statement批处理 创建数据库表 添加数据

package cn.itheima.jdbc;import java.sql.Connection;import java.sql.ResultSet;import java.sql.Statement;import org.junit.Test;import cn.itheima.utils.JDBCUtils;/* create database day10batch; use day10batch; create table batchDemo( id int primary key auto_increment, name varchar(20) ); insert into batchDemo values(null,'aaaa'); insert into batchDemo values(null,'bbb'); insert into batchDemo values(null,'cc'); insert into batchDemo values(null,'d'); */public class StatementBatch {Connection con = null;Statement sta = null;ResultSet rs = null;@Testpublic void update() {try {con = JDBCUtils.getConnection();sta = con.createStatement();sta.addBatch("create database day10batch");sta.addBatch("use day10batch");sta.addBatch("create table batchDemo("+"id int primary key auto_increment,"+"name varchar(20)"+")");sta.addBatch("insert into batchDemo values(null,'aaaa')");sta.addBatch("insert into batchDemo values(null,'bbbb')");sta.executeBatch();} catch (Exception e) {e.printStackTrace();throw new RuntimeException();} finally {JDBCUtils.closeResource(rs, sta, con);}}}
2.PrepareStatement 批处理 添加100条数据

package cn.itheima.jdbc;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import org.junit.Test;import cn.itheima.utils.JDBCUtils;public class PsBatch {Connection con = null;PreparedStatement ps = null;ResultSet rs = null;@Testpublic void update(){try{con=JDBCUtils.getConnection();ps=con.prepareStatement("insert into batchDemo values(null,?)");for(int i=0;i<100;i++){ps.setString(1, "aaa"+i);ps.addBatch();}ps.executeBatch();}catch (Exception e) {e.printStackTrace();throw new RuntimeException();}finally{JDBCUtils.closeResource(rs, ps, con);}}}

3.比较

Statement 数据变换形式比较大的时候使用

PrepareStatement数据不变化的时候使用

0 0