您的位置:首页 > 其它

jdbc批量插入数据(同时处理数据重复)

2015-05-11 00:00 495 查看
摘要: 通过jdbc的executeBatch来进行批量的数据插入操作。并在插入过程中同时处理数据的重复问题(主键,唯一约束等等)

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,然后再最后进行一次手动事务提交。

上面的这种方式在对于对数据的重复性没有要求时就已经足够使用了。如果需要忽略重复的数据时,则将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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: