Statement批处理
import cn.tedu.jdbc.utiles.JDBCUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
/*
*
* 优点:可以执行不同语义的sql
* 缺点:
* 1.没有预编译(避免sql注入)
* 2.要发送完整的sql语句
* 3.语义即使相同也要发送完整的sql语句
*
* */
public class StatementBatchDemo {
public static void main(String[] args) {
Connection conn=null;
Statement stat=null;
try {
conn = JDBCUtils.getConnection();
stat = conn.createStatement();
//添加sql语句到批处理中
stat.addBatch("create table t1(id int,name varchar(10))");
stat.addBatch("insert into t1 values(1,'鸣人')");
stat.addBatch("insert into t1 values(2,'雏田')");
stat.addBatch("insert into t1 values(3,'二柱子')");
stat.addBatch("insert into t1 values(4,'自来也')");
//通知数据库服务器执行批处理操作
stat.executeBatch();
System.out.println("批处理执行完成");
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(conn,stat,null);
}
}
}
PreparedStatement批处理
import cn.tedu.jdbc.utiles.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
* 优点:1.具有预编译功能可以避免sql注入
* 2.由于是将sql的主干语句发送到数据库服务器上所以不需要重复发送执行效率较高
* 3.只重复发送参数不发送完整的sql语句所以执行效率较高
* 缺点:不能执行语义不同的sql语句
*
* */
public class PreparedStatementDemo {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement ps=null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement("insert into t1 values(?,?)");
for(int i=5;i<=1000;i++){
ps.setInt(1,i);
ps.setString(2,"name"+i);
//添加到批处理中
ps.addBatch();
if(i%100==0){
//满足一百条数据来执行一次批处理
ps.executeBatch();
//执行过的批处理进行清空
ps.clearBatch();
System.out.println("第"+i/100+"次批处理执行完毕。。。");
}
}
//执行批处理(执行之前没有执行的批处理里的sql语句)
ps.executeBatch();
System.out.println("全部执行完毕!!!");
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(conn,ps,null);
}
}
}