コンテンツ
1.PreparedStatementと連絡先のステートメントの違い
1.preparedStatementとStatementの関係:
4.提出のタイミングを変更して提出数を制御し、効率を向上させます
1.PreparedStatementと連絡先のステートメントの違い
1.preparedStatementとStatementの関係:
1.これらはすべて、Sun Companyのjdbcパッケージングクラスのインターフェイスであり、外部接続には属していません。
2.reparedStatementは、ステートメントインターフェイスのサブインターフェイスです。
2.違い:
1. PreparedStatementはシステムパフォーマンスを最大化できます。PreparedStatementはSQLステートメントをプリコンパイルし、DBServerはプリコンパイルされたSQLステートメントのパフォーマンスを最適化します。プリコンパイルされたSQLステートメントは、再コンパイルせずに後続のバッチ挿入で直接使用できるため、パフォーマンスが向上します。読み取りと書き込みの速度
2.ステートメントステートメントでは、同じSQLステートメントを操作しても、挿入内容が異なるため、SQLステートメントを再度コンパイルする必要があり、読み取りと書き込みの速度に影響します。
3. PreparedStatementは、SQLインジェクションを防ぐことができます。
4. PreparedStatementを使用すると、BLobストリームファイルデータを挿入できますが、StatementはBlobデータを挿入できません
5.ステートメントデータの使用には文字列が必要であり、操作は面倒であり、SQLインジェクションもあります
2.データをデータに挿入するバッチの段階的な最適化
1.ステートメントを使用する
2.PreparedStatementを使用して挿入します
//批量插入方式二:使用PreparedStatement插入
public void testInsertInfo() throws Exception {
Connection conn = null;
PreparedStatement pst = null;
String sql = "insert into user_tab(id,name) values(?,?)";
try {
long start = System.currentTimeMillis();
conn = JDBCUtils.getConnection();
pst = conn.prepareStatement(sql);
for (int i = 1; i <20000 ; i++) {
pst.setObject(1,i);
pst.setObject(2,"name");
pst.execute();
}
long end = System.currentTimeMillis();
System.out.println("采用preparedStatement方式插入20000条数据花费的时间为:"+(end - start));
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,pst);
}
}
3.バッチキャッシュを使用して挿入します
//批量插入方式三:使用批处理插入
/*
1.使用 添加batch :addBatch() 执行batch:executeBatch() 清空Batch(): clearBatch();
2.在连接数据的url后面配置这句话:
?rewriteBatchedStatements=true
3.批量插入数据使用的jdbc.jar必须实在5.7版本以上才支持
*/
@Test
public void testInsertInfo2() {
Connection conn = null;
PreparedStatement pst = null;
String sql = "insert into user_tab(id,name) values(?,?)";
try{
long start = System.currentTimeMillis();
conn = JDBCUtils.getConnection();
pst = conn.prepareStatement(sql);
for (int i = 1; i <=20000 ; i++) {
pst.setObject(1,i);
pst.setObject(2,"name"+i);
//1,添加batch
pst.addBatch();
//2.执行batch()
if (i % 500 == 0){
pst.executeBatch();
//清空batch
pst.clearBatch();
}
}
long end = System.currentTimeMillis();
System.out.println("采用batch插入20000条数据花费时间为:"+ (end - start));
}catch (Exception e){
e.printStackTrace();
}finally {
}
}
4.提出のタイミングを変更して提出数を制御し、効率を向上させます
public void testInsertInfo3(){
Connection conn = null;
PreparedStatement pst = null;
String sql = "insert into user_tab(id ,name) values(?,?)";
try {
long start = System.currentTimeMillis();
conn = JDBCUtils.getConnection();
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
for (int i = 1; i <= 200000; i++) {
pst.setObject(1,i);
pst.setObject(2,"name"+i);
//添加缓存
pst.addBatch();
if(i % 500 == 0){
//执行缓存
pst.executeBatch();
//清空缓存
pst.clearBatch();
}
}
conn.commit();
long end = System.currentTimeMillis();
System.out.println("采用设置不允许自动提交的方式的花费的时间:"+(end - start));
}catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.closeResource(conn,pst);
}
}