批量插入數據

這段時間遇到一個將記事本文件97萬條記錄導入到數據庫中,其中也就兩個字段結構這樣:00000001-89567428
若是用普通的方法要導入到數據庫大概須要4個小時,太費時間。用Batch只須要16秒,下面我將方法寫下來,遇到一樣問題的朋友能夠進行參考下:
//先寫個讀取文本文件的行數的方法
public static int getTotalLines(String filePath){
try{
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filePath)));
int totalLines = 0;
while(lnr.readLine()!=null){
totalLines++;
}
return totalLines;
}catch(Exception e){
    throw new RuntimeException(e);
}
}
//獲取數據的連接,這裏寫的是mysql的,你能夠依葫蘆畫瓢,oracle和sqlserver.
public static Connection getConn(){
try{
Class.forName(com.mysql.driver);//這裏你要根據你的mysql jar來得到驅動
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/database","用戶名","密碼");
return conn;
}catch(Exception e){
throw new RuntimeException(e);
}
}
//下面就是要對數據進行導入了,能夠寫一個Main方法
public static void main(String args[]){
String filePath = "D:\\xx.txt";
String sql = "insert into table(xxx,bbb) valuese(?,?) ";
Connection conn = getConn();
int totalLines = getTotalLines(filePath);
try{
conn.setAutoCommit(false);//這裏亮點,關閉Connection 的自動提交,改成手動提交
PreparedStatement ps = conn.createPreparedStatement(sql);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new FIle(filePath))));
String line = br.readLine();
int i = 0;
while(line !=null){
i++;
String[] lines = line.split("-");
ps.setString(1,lines[0]);
ps.setString(2,lines[1]);
ps.addBatch();//亮點,進行批量處理
if(i%50000 ==0){//若是批量到5萬,進行一次批處理
ps.executeBatch();
conn.commit();
}
if(i == totalLines){//當達到最後的一條記錄的時候再進行批處理一次。
ps.executeBatch();
conn.commit();
}
 
 
}
}catch(Exception e){
e.printStackTrace();
}
}
--------------------------------------------------------------------------------------------------------
這樣大概16秒鐘就能處理完了,比起讓數據庫自動提交,一個一個插入快得不是一兩個等級。
相關文章
相關標籤/搜索