package pers.C082701.p04;
import pers.C082701.p04.Utils.Utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* <p>
* ************************** 使用PrepareStatement预编译语句执行批处理 ************************************************
* 步骤:
* 第一步:获取连接:
* 第二步:创建命令;
* 第三步:设置自动提交为false
* 第四步:设置参数
* 第五步:添加SQL语句到批处理中;
* 第六步:执行命令;
* 第七步:提交;
*
* 注意事项:
* 要设置自动提交为false,最后要手动提交一下
* 配置文件里面要有:&rewriteBatchedStatements=true这样一个配置,提高批处理的速度;
*/
public class Test01 {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement=null;
try {
//第一步:获取连接
connection=Utils.getConnection();
// 第二步:创建命令
preparedStatement= connection.prepareStatement("insert into stu values (?,?,?)");
// 第三步:设置自动提交为false
connection.setAutoCommit(false);
// 第四步:设置参数:
long l = System.currentTimeMillis();
for (int i = 1; i <10006 ; i++) {
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "路人"+i+"");
preparedStatement.setInt(3, (i+60)%50);
preparedStatement.addBatch(); // 在创建的命令语句对象上添加上面这一条SQL语句到批处理中。
// 因为一次处理的语句太多,影响效率,所以进行分批处理:每100条数据进行一次批处理,之后清空,再开始下个100条数据......
if (i % 100 == 0) {
int[] i1 = preparedStatement.executeBatch(); //执行(这一批的)所有SQL语句;
System.out.println( i1.length);
preparedStatement.clearBatch();// 这一批语句执行完,已经没用了,进行清空一下;
}
}
// 这放一个executeBatch()方法的作用是:如果最后一批SQL语句不满1000条,则这个方法将这不满1000条的“尾巴”语句给执行了,保证了不会漏下一些语句没有执行;
int[] ints = preparedStatement.executeBatch();
System.out.println( ints.length);
connection.commit(); // 提交一下
System.out.println( "提交成功");
long l1 = System.currentTimeMillis();
System.out.println( l1-l);
// 这里就是,如果想执行更新语句的话,需要另外再创建一个命令对象
// 因为预编译的,一个命令对象只能添加一种语句;
// connection.prepareStatement("update ......")
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Statment批处理和PrepareStatment批处理区别:
1)Statment批处理可以添加不同Sql语句,而PrepareStatment只能添加一种sql语句
2)PrepareStatment效率比Statment高,而且更安全。