jdbc批量數據插入的代碼
1899942 ,一
1899944 ,二
1899946 ,三 1899948 ,四
1899950 ,五
1899952 ,六
1899954 ,和
1899956 ,在 1899958 ,的
1899960 ,對 1899962 ,需 1899964 ,大規模
1899966 ,壓力 1899968 ,大城市 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。 有幾萬條這樣的數據需要插入數據庫public class Main { public static void main(String[] args) throws Exception{ String sql = "insert into mobile_place(number,place) values(?,?)"; int count = 0;//計數器 Connection conn = JDBCUtil.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); try { InputStreamReader is = new InputStreamReader(new FileInputStream(new File("D:/CC.txt")),"utf-8"); BufferedReader br = new BufferedReader(is); while(br.readLine() != null){ conn.setAutoCommit(false);//設置數據手動提交,自己管理事務 count++;//沒讀取一行數據,計數器+1 String str = br.readLine().toString().trim();//讀取一行數據 String s1 = str.substring(0, str.indexOf(","));//取逗號以前的一段 String s2 = str.substring(str.indexOf(",")+1,str.length());//取逗號之后的一段 pstmt.setString(1, s1); pstmt.setString(2, s2); pstmt.addBatch();//用PreparedStatement的批量處理
if(count%500==0){//當增加了500個批處理的時候再提交 pstmt.executeBatch();//執行批處理 conn.commit();//提交 conn.close();//關閉數據庫 conn = JDBCUtil.getConnection();//重新獲取一次連接 conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql); } System.out.println("已插入"+count+"條數據"); } if(count%500!=0){//while循環外的判斷,為了防止上面判斷后剩下最后少于500條的數據沒有被插入到數據庫 pstmt.executeBatch(); conn.commit(); } pstmt.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } } 500可以自己增大,執行效率很高。比單挑執行再插入快多了
getConnection()為獲取數據庫連接 public static Connection getConnection(){ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { conn = DriverManager.getConnection(url, userName, password); } catch (SQLException e) { e.printStackTrace(); } return conn; }</pre>