比如sql语句中有主键冲突,批量执行时,一条冲突,会导致整个batch执行失败,一条记录也插不进去。实例代码如下:
public void test()
{
Connection conn = null;
PreparedStatement pStmt = null;
String sql = "insert into user(uid, screen_name) values(?, ?)";
try {
conn = DB.getConn();
conn.setAutoCommit(false);
pStmt = DB.getpStmt(conn, sql);
pStmt.setString(1, "111111");
pStmt.setString(2, "aaaaaa");
pStmt.addBatch();
pStmt.setString(1, "222222");
pStmt.setString(2, "bbbbbb");
pStmt.addBatch();
pStmt.setString(1, "333333");
pStmt.setString(2, "cccccc");
pStmt.addBatch();
pStmt.setString(1, "333333");
pStmt.setString(2, "dddddd");
pStmt.addBatch();
pStmt.executeBatch();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally
{
try {
if(pStmt != null)
{
pStmt.close();
}
if(conn != null)
{
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
运行会提示如下错误:
java.sql.BatchUpdateException: Duplicate entry '333333' for key 'PRIMARY'
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:652)
at DAO.UserDAO.test(UserDAO.java:38)
at DAO.UserDAO.main(UserDAO.java:63)
有没有什么方法,在执行batch时,遇到一条sql执行失败,能够忽略它继续执行?
我能想到的是,利用异常处理部分,找到是哪几行有问题,删掉再重新执行,挺麻烦,好像不太容易实现
PS:用的是java语言,mysql数据库
Java MySql
------解决方案--------------------
一条一条执行不行吗