数据库插入优化

1.一条SQL语句插入多条数据:

  关闭自动提交,使用preparedStatement

  1. Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123");  
  2. // 关闭自动提交,默认情况下每执行一条sql提交一次  
  3. connection.setAutoCommit(false);  
  4. PreparedStatement statement = connection.prepareStatement("INSERT INTO insert_table VALUES(?, ?)");   
  5. //记录1  
  6. statement.setString(1, "2012-12-27 11:11:11");   
  7. statement.setString(2, "userid_0");   
  8. statement.setString(3, "content_0");   
  9. statement.setInt(4, 0);   
  10. statement.addBatch();   
  11. //记录2  
  12. statement.setString(1, "2012-12-27 12:12:12");   
  13. statement.setString(2, "userid_1");   
  14. statement.setString(3, "content_1");   
  15. statement.setInt(4, 1);  
  16. statement.addBatch();   
  17. //记录3  
  18. statement.setString(1, "2012-12-27 13:13:13");   
  19. statement.setString(2, "userid_2");   
  20. statement.setString(3, "content_2");   
  21. statement.setInt(4, 2);   
  22. statement.addBatch();   
  23. //批量执行上面3条语句.   
  24. int [] counts = statement.executeBatch();   
  25. //Commit   
  26. connection.commit();  

  一是减少SQL语句解析的操作, 只需要解析一次就能进行数据的插入操作,二是SQL语句较短,可以减少网络传输的IO

2. 在事务中进行插入处理。

  使用事务可以提高数据的插入效率,这是因为进行一个INSERT操作时,MySQL内部会建立一个事务,在事务内进行真正插入处理。通过使用事务可以减少数据库执行插入语句时多次“创建事务,提交事务”的消耗,所有插入都在执行后才进行提交操作。

3.先把所有索引都删除,待插入完毕,再重新建索引,它的意义是:插入时,只写数据,不写索引。全部插入完毕,再创建索引,索引文件只需创建一次,避免频繁更新

原文地址:https://www.cnblogs.com/zawjdbb/p/7497571.html