由於項目需要,需要將一個6M的txt中的數據插入到oracle數據表中。txt中的數據是每行一個詞。經過統計,詞總數是505040。為了看起來方便,我將我的所有方法寫在類入口中,數據庫的信息我會用test代替,代碼如下。
public static void main(String[] args) throws IOException, Exception { // TODO Auto-generated method stub Connection conn = null; Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:test", "test", "test"); conn.setAutoCommit(false); PreparedStatement pst = conn .prepareStatement("insert into yq_seq_word values(seq_yq_seq_word.nextval,?)"); InputStreamReader isr = new InputStreamReader(new FileInputStream( new File("C:/Users/Press-Lab/Desktop/test.txt")), "utf-8"); BufferedReader read = new BufferedReader(isr); String s = null; int i = 1; long start = System.currentTimeMillis(); while ((s = read.readLine()) != null) { // 當數據滿100條批量插入 if (i % 100 == 0) { // 語句執行完畢,提交本事務 pst.executeBatch(); // 此處的事務回滾是必須的,網上很多代碼沒有處理,會導致插入數據不完整。 try { conn.commit(); } catch (Exception e) { conn.rollback(); } } else { pst.setString(1, s); pst.addBatch(); } System.err.println(s); i++; } // 由於每次達到100條插入,如果數據不為100的倍數的話,最后一次會剩下一些。下面的代碼正好處理剩下的數據 // 語句執行完畢,提交本事務 pst.executeBatch(); try { conn.commit(); } catch (Exception e) { conn.rollback(); } long end = System.currentTimeMillis(); // 此處是打印插入效果 System.out.println("插入" + i + "條,耗時" + (end - start)); read.close(); }
以下是效果的打印。
插入505040條,耗時22796