/*
准备一张表,向这张表中插入10万条记录,但是
使用批处理操作,记录耗时。
*/
import java.sql.*;
public class Test02
{
public static void main(String[] args){
Connection conn = null;
PreparedStatement ps = null;
try{
//1.注册驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:name", "scott","tiger");
//3.获取预编译的数据库操作对象
String sql = "INSERT INTO BATCH_TAB(ID,NAME) VALUES(?,?)";
ps = conn.prepareStatement(sql);
//4.执行SQL语句
long begin = System.currentTimeMillis();
for(int i=1;i<=100000;i++){
ps.setInt(1,i);
ps.setString(2,"NAME" + i);
//添加到batch中。
ps.addBatch();
//此处的500是自己随便定义的,实际情况中 这个数字的设定跟执行效率有很大关系
if(i%500==0){
//执行
ps.executeBatch();
ps.clearBatch();
}
}
ps.executeBatch();
long end = System.currentTimeMillis();
System.out.println("耗时:"+(end-begin)/1000+"秒");
}catch(Exception e){
e.printStackTrace();
}finally{
//5.释放资源
if(ps!=null){
try{
ps.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(conn!=null){
try{
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}