MySQL事务删除与Java
我有这样的桌子:MySQL事务删除与Java,java,mysql,transactions,foreign-keys,constraints,Java,Mysql,Transactions,Foreign Keys,Constraints,我有这样的桌子: Table A: `id | name` Table B: `id | A_id | ....` A_id is a foreign key to Table A, the Engine is InnoDB 这是失败的代码: String[] cleanupQueries = new String[] { "DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name = 'test')",
Table A:
`id | name`
Table B:
`id | A_id | ....`
A_id is a foreign key to Table A, the Engine is InnoDB
这是失败的代码:
String[] cleanupQueries = new String[] { "DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name = 'test')",
"DELETE FROM A WHERE name = 'test'" };
Connection connection;
try {
connection = DriverManager.getConnection(getConnectionString());
connection.setAutoCommit(false);
} catch (SQLException e) {
throw new RuntimeException("Error establishing a database connection!");
}
try {
for(String cleanupQuery : cleanupQueries) {
PreparedStatement statement = connection.prepareStatement(cleanupQuery);
statement.executeUpdate(); //FAILS WHEN EXECUTING THE SECOND QUERY
}
} catch(SQLException e) {
throw new RuntimeException("Error while executing the queries in the transactional context!");
}
try {
connection.commit();
} catch (SQLException e) {
rollback(connection);
throw new RuntimeException("Error while comitting!");
}
我得到的例外是:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:无法删除或更新父行:外键约束失败('DATABASE/TABLE',约束'FK_B_a'外键('FK_a')引用DEL上的'a'('ID')
数据库不允许我在还剩下B的时候删除A,但是第一个查询删除了所有B。我想删除所有的B和A,他们只参考完全
我不想将表更改为具有级联删除。如何使代码正常工作?导致错误的原因是
外键引用了表A id,因此如果要删除F_键,首先应该删除该外键的子引用值,然后才可以删除父项
如果我错了,请更正。删除外键约束时,只需添加级联即可。删除原始父项时,子表项将自动删除。请尝试:
"DELETE FROM B WHERE A_id = (SELECT id FROM A WHERE name IN 'test')"
由于在同一事务中删除了子行,因此删除的行仍然可见,因此无法删除父行。
这可能是因为连接上的事务隔离设置。我会尝试不同的级别,看看哪个级别允许它。你是对的,但我不想在事务上下文之外进行。我对数据库结构没有影响。我需要有计划地做,确保交易只能强制完成。