jdbc批量插⼊数据(同时处理数据重复)
批量更新sql语句private static boolean insert(List<SpPage> list) {
Connection connection = getConnection();
if (null == connection) {
}
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 = (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();
}
connectionmit();
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。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。