private static boolean insert(List<SpPage> list) { Connection connection = getConnection(); if (null == connection) { System.err.println("數據庫鏈接失敗"); } try { String sql = "INSERT INTO sp_page_test (title, web_site, type, url, status) VALUES (?, ?, ?, ?, ?)" ; PreparedStatement prest = connection .prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); connection.setAutoCommit(false); for (int x = 0; x < list.size(); x++) { SpPage sp = list.get(x); prest.setString(1, sp.getTitle()); prest.setString(2, sp.getWebSite()); prest.setString(3, sp.getType()); prest.setString(4, sp.getUrl()); prest.setString(5, sp.getStatus()); prest.addBatch(); } prest.executeBatch(); connection.commit(); connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; }
使用executeBatch方式進行批量插入的關鍵在於設置setAutoCommit爲false,而後再最後進行一次手動事務提交。java
上面的這種方式在對於對數據的重複性沒有要求時就已經足夠使用了。若是須要忽略重複的數據時,則將sql語句改成web
String sql = "INSERT ignore INTO sp_page_test (title, web_site, type, url, status) VALUES (?, ?, ?, ?, ?)" ;
使用insert ignor 能夠忽略掉重複的數據。若是但願更新重複的數據,則能夠使用sql
String sql = "INSERT INTO sp_page_test (title, web_site, type, url, status) VALUES (?, ?, ?, ?, ?)" + "ON DUPLICATE KEY UPDATE title=values(title)"
insert ON DUPLICATE KEY UPDATE 能夠在數據重複時進行更新。數據庫
title=values(title)的意思是將舊記錄的title更新爲新紀錄的title。url