private static boolean insert(List 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,然后再最后进行一次手动事务提交。
上面的这种方式在对于对数据的重复性没有要求时就已经足够使用了。如果需要忽略重复的数据时,则将sql语句改为
String sql = "INSERT ignore INTO sp_page_test (title, web_site, type, url, status) VALUES (?, ?, ?, ?, ?)" ;
使用insert ignor 可以忽略掉重复的数据。如果希望更新重复的数据,则可以使用
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。