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