2012-07-05 68 views
1

我目前正在編寫一個Java程序,它循環遍歷4000個XML文件的文件夾。提高SQL的速度從JDBC插入XML列(SQL Server)

使用for循環,它從每個文件中提取XML,將其分配給String'xmlContent',並使用PreparedStatement方法setString(2,xmlContent)將String插入存儲在SQL Server中的表中。

列'2'是XML類型的一個稱爲'數據'的列。

該過程起作用,但速度很慢。它每7秒向表格中插入約50行。

有沒有人有任何想法可以加快這個過程?

代碼:

{ ...declaration, connection etc etc 
     PreparedStatement ps = con.prepareStatement("INSERT INTO Table(ID,Data) VALUES(?,?)"); 

     for (File current : folder.listFiles()){ 
      if (current.isFile()){ 
       xmlContent = fileRead(current.getAbsoluteFile()); 
       ps.setString(1, current.getAbsoluteFile()); 
       ps.setString(2, xmlContent); 
       ps.addBatch(); 

       if (++count % batchSize == 0){ 
        ps.executeBatch(); 
       } 

      } 
     } 
     ps.executeBatch(); // performs insertion of leftover rows 
     ps.close(); 
} 

private static String fileRead(File file){ 

     StringBuilder xmlContent = new StringBuilder(); 

     FileReader fr = new FileReader(file); 
     BufferedReader br = new BufferedReader(fr); 
     String strLine = ""; 
     br.readLine();  //removes encoding line, don't need it and causes problems 
     while ((strLine = br.readLine()) != null){ 
      xmlContent.append(strLine); 
     } 
     fr.close(); 

     return xmlContent.toString(); 
    } 

回答

2

只是從一個小閱讀和快速測試 - 它看起來像你可以通過你的連接關閉自動提交得到一個體面的加速。我看到的所有批處理查詢教程都會推薦它。如http://www.tutorialspoint.com/jdbc/jdbc-batch-processing.htm

把它關閉 - 然後在你想要的地方放下一個顯式的提交(在每個批處理結束時,在整個函數結束時等)。

conn.setAutoCommit(false); 
PreparedStatement ps = // ... rest of your code 

// inside your for loop 

    if (++count % batchSize == 0) 
    { 
      try { 
      ps.executeBatch(); 
      conn.commit(); 
      } 
      catch (SQLException e) 
      { 
       // .. whatever you want to do 
       conn.rollback(); 
      } 
    } 
0

最好使讀取和寫入並行。

使用一個線程讀取文件並存儲在緩衝區中。 使用另一個線程從緩衝區中讀取並在數據庫上執行查詢。

您可以使用多個線程並行寫入數據庫。這應該會給你更好的表現。

我建議你遵循這種MemoryStreamMultiplexer方法,你可以讀取一個線程中的XML文件並存儲在一個緩衝區中,然後使用一個或多個線程從緩衝區中讀取並對數據庫執行。

http://www.codeproject.com/Articles/345105/Memory-Stream-Multiplexer-write-and-read-from-many

這是一個C#實現,但你的想法。