在java中使用jdbc原生事务操作时。报错
Exception in thread "main" java.sql.SQLException: errCode = 2, detailMessage = Transaction insert can not insert into values and insert into select at the same time
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:764)
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:648)
逻辑就是先清空表,然后在做插入。代码如下:
jdk:1.8
mysql driver版本:8.0.22
/**
* 同步更新表数据,保证事务
* @param tableName
* @throws SQLException
*/
public static void syncUpdateTableData(String tableName, List<JSONObject> allRecord) throws SQLException {
Connection conn = getConnection();
try {
if(BaseHelper.isEmpty(allRecord)){
//无临时数据
System.out.println("未生成临时数据");
return;
}
// conn.setAutoCommit(false);
tableName = "test";
// 开启事务
beginTran(conn);
// 清空旧数据
String sql = String.format("DELETE FROM %s;", tableName);
String sql1 = "INSERT INTO test values ('1')";
try(Statement statement = conn.createStatement()){
statement.execute(sql);
statement.execute(sql1);
}
commitTran(conn);
}catch (SQLException e) {
System.out.println("table ===>" + tableName + "发生异常,数据回滚!!!!");
rollbackTran(conn);
throw e;
}finally {
conn.close();
}
}
/**
* 提交事务
* @param conn
* @throws SQLException
*/
private static void commitTran(Connection conn) throws SQLException {
Statement beginStatement = conn.createStatement();
beginStatement.executeUpdate("COMMIT;");
}
/**
* 回滚事务
* @param conn
* @throws SQLException
*/
private static void rollbackTran(Connection conn) throws SQLException {
Statement beginStatement = conn.createStatement();
beginStatement.executeUpdate("ROLLBACK;");
}
/**
* 开启事务
* @param conn
* @throws SQLException
*/
private static void beginTran(Connection conn) throws SQLException {
conn.setAutoCommit(false);
try (Statement beginStatement = conn.createStatement();) {
beginStatement.execute("BEGIN WITH LABEL my_unique_label_" + System.currentTimeMillis() + ";");
}
}
该如何修复这个错误?