我已将Java连接到SQL并希望从不同的表中删除两行,但是我的Java方法存在问题。我试图从两个表中删除因为我无法从Table1删除ID,因为它被table2引用。有关修复此问题的建议吗?
public void delete() throws SQLException
{
DataConnection connection = new DataConnection();
String query = " DELETE FROM " + Table1 + " WHERE ID = " + id + " AND " + " DELETE FROM " + Table2 + " WHERE ID = " + id;
connection.updateData(query);
connection.closeConnection();
}
答案 0 :(得分:1)
按顺序执行查询,您无法在一个查询中执行此操作 -
String s2 = " DELETE FROM table2 WHERE ID = " + id;
// Execute s2 here
String s1 = "Delete from table1 WHERE ID = " + id ;
// Execute s1 here
试试这个 -
public void delete() throws SQLException {
DataConnection connection = new DataConnection();
String query1 = " DELETE FROM " + table2 + " WHERE ID = " + id;
String query2 = " DELETE FROM " + Table1 + " WHERE ID = " + id;
// String query = query1 + " " + query2;
connection.updateData(query1);
connection.updateData(query2);
connection.closeConnection();
答案 1 :(得分:1)
See Always child references should be deleted first.
if there are any references to parent table then parent table can not be deleted.
but if the parent table has cascade delete then it can delete all child tables while deleting table.
in your case table1 is parent as it is referencing from one of the child table table2.
so delete table2 first then any other tables if they are also referencing table1's id.
then try to delete table1.
it should work.
let me know for any issues.
答案 2 :(得分:1)
让您的方法可重复使用:
public void delete(String table, long id) throws SQLException {
DataConnection connection = new DataConnection();
String query = " DELETE FROM " + table + " WHERE ID = " + id;
connection.updateData(query);
connection.closeConnection();
}
然后只需调用:
delete(Table1, id);
delete(Table2, id);
但这取决于新连接创建的成本。