1. 程式人生 > >jdbc連線Oracle/MySQL資料庫進行批量匯入操作,如何提高效率???

jdbc連線Oracle/MySQL資料庫進行批量匯入操作,如何提高效率???

package com.test.main;

import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Date;

import com.test.jdbc.OracleDBConnection;

public class Test {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub	
		//得到Oracle資料庫連線
		Connection conn=new OracleDBConnection().getConnection();
		conn.setAutoCommit(false);//設定為不自動提交
		
		 String sql="INSERT INTO  GPS_LOG_cxc "  
	                + "(licenseplateno ,in_date,gps_time,longitude,latitude,height,speed, direction , eff, car_stat1, car_stat2)"  
	                +"VALUES(?,?,?,?,?,?,?,?,?,?,?)";  
	        PreparedStatement pstmt=conn.prepareStatement(sql);  
	          
	        
	        //每n條命令commit一次  
	        int n=10000;  
	        int[] updateCounts=null;   
	        //記錄起始時間   
	        long startTime=System.currentTimeMillis();  
	        //記錄命令執行失敗數  
	        long faileNum=0;  
	        //記錄執行commit次數  
	        long commitNum=0;  
	        for(int i=1;i<=1000000;i++){  
	        	pstmt.setString(1, "粵A434XX");  
		        pstmt.setDate(2, new java.sql.Date(new Date().getTime()));  
		        pstmt.setDate(3, new java.sql.Date(new Date().getTime()));  
		        pstmt.setString(4, "+113.36671");  
		        pstmt.setString(5, "+23.08077");  
		        pstmt.setString(6, "000");  
		        pstmt.setString(7, "100");  
		        pstmt.setString(8, "000");  
		        pstmt.setString(9, "1");  
		        pstmt.setString(10,"1" );  
		        pstmt.setString(11, "8");  
	            pstmt.addBatch();  
	            if(i%n==0){  
	                try {  
	                    pstmt.executeBatch();  
	                    conn.commit();  
	                    //pstmt.clearBatch();
	                    commitNum++;  
	                    System.out.println("--commit-- ");  
	                    } catch (BatchUpdateException bue) {  
	                        // TODO Auto-generated catch block  
	                            faileNum++;  
	                            updateCounts=bue.getUpdateCounts();  
	                        }  
	                }  
	        }  
	          
	        pstmt.executeBatch();  
	        conn.commit();  
	        //pstmt.clearBatch();  
	          
	        long endTime=System.currentTimeMillis();
	        pstmt.close();  
	        conn.close();  
	          
	        long time=(endTime-startTime)/1000;  
	        //統計資料  
	        System.out.println("每次提交:"+n+"條");  
	        System.out.println("提交次數:"+commitNum);  
	        System.out.println("失敗次數:"+faileNum);  
	        System.out.println("用時:"+time+"秒");  
	}

}