轉載請注明原文地址:http://www.cnblogs.com/ygj0930/p/5861959.html
使用JDBC連接數據庫時,如果插入的數據量大,一條一條地插入數據會變得非常緩慢。此時,我們需要用到預處理。
查閱Java開發文檔,我們可以看到:
接口 PreparedStatement
表示預編譯的 SQL 語句的對象。
SQL 語句被預編譯並存儲在 PreparedStatement
對象中。然后可以使用此對象多次高效地執行該語句。
我的理解是,preparedstatement對象相當於sql語句執行前的一個加工站,對sql語句進行具體的數據填充。
大概的使用流程是:
1:使用BufferedString構建一個同時插入N條數據的語句模版;
2:利用模版生成字符串語句,將該語句作為參數構建一個PreparedStatement對象pst,意指用pst對參數語句進行預處理;
3:用pst對象調用方法對參數語句進行預處理:pst.setXX(index,value)等語句把參數語句進行具體的數據填充;
4:執行經過pst處理過后的具體sql語句:pst.execute();
5:關閉pst對象;
畫圖理解:
代碼示例:
import java.net.*; import java.io.*; import java.sql.*; public class Insert { public static void main(String[] args) { Connection conn=null; try{ Class.forName("com.mysql.jdbc.Driver"); conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/inserttest","root","123456"); conn.setAutoCommit(false); //使用緩沖字符串構造一個同時插入10000條數據的語句模版 StringBuffer sqlBuffer = new StringBuffer( "insert into test (Col1,Col2,Col3) values"); sqlBuffer.append("(?,?,?)"); for (int j = 2; j <= 10000; j++) { sqlBuffer.append(",(?,?,?)"); } sqlBuffer.append(";"); String sql = new String(sqlBuffer); //SQL語句被預編譯並存儲在 PreparedStatement 對象中。然后可以使用此對象多次高效地執行該語句。在使用該語句時可以根據下標自行更改具體數據 PreparedStatement pst = conn.prepareStatement(sql); System.out.println("start!"); Long beginTime = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { System.out.println("No."+(i+1)+"round..."); for (int j = 0; j < 10000; j++) { //每次插入時,具體的數據通過pst.setXXX(index,value)來賦值 pst.setInt(3 * j + 1, (int) (Math.random() * 11)+1); pst.setInt(3 * j + 2, (int) (Math.random() * 112)+2); pst.setInt(3 * j + 3, (int) (Math.random() * 133)+5); } //每條sql語句插入10000條數據,執行100條sql pst.execute(); } conn.commit(); pst.close(); Long endTime = System.currentTimeMillis(); System.out.println("end!"); System.out.println("total time: " + (double) (endTime - beginTime)/1000 + " s"); System.out.println(); }catch(Exception ex){ } } }