簡體   English   中英

使用Java和SQL刪除兩個表中的行

[英]Delete Rows in Two Tables with Java and SQL

我已將Java連接到SQL,並想從不同的表中刪除兩行,但是我的Java方法有問題。 我試圖從兩個表中刪除,因為我無法從表1中刪除ID,因為它是由表2引用的。 關於修復此問題有什么建議嗎?

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();
    }

按一個順序依次執行查詢,您無法在一個查詢中進行查詢-

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();
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.

使您的方法可重用:

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);

但這取決於創建新連接的成本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM