0

I have a bizarre issue where I can execute a stored procedure from the command line, and directly on the mysql instance, however, when I run the stored procedure from Java, I am getting an error: Cannot delete or update a parent row: a foreign key constraint fails

My code is:

public void runCleanCustomerDataStoredProcedures() {

        ResultSet rs =  Db.getInstance().runQuery("SELECT DATABASE();");
        String database = null;
        try {
            while (rs.next()) {
                database = rs.getString("DATABASE()");
            }
        } catch (SQLException e) {
            logger.error(e.getMessage());
        }
        ArrayList<String> batchIDs = Db.getInstance().getDistinctFieldsFromTable("id","batch");
        Db.getInstance();
        for (String batchID : batchIDs){
            String query = "{ call " + database + ".delete_batch_and_data(?,?,?,?)}";
            ExecuteStoredProcedure(query, batchID);
        }

        ArrayList<String> custIDs = Db.getInstance().getDistinctFieldsFromTable("id","customer");
        Db.getInstance();
        for (String custID : custIDs){
            String query = "{ call " + database + ".delete_customer_and_data(?,?,?,?)}";
        
            ExecuteStoredProcedure(query,custID);
        }
        Db.destroyInstance();
    }

public void ExecuteStoredProcedure(String query, String id){
        CallableStatement callableStatement = null;
        try {
            callableStatement  = con.prepareCall(query);
            callableStatement.setString(1,id);
            callableStatement.setString(2,"");
            callableStatement.setString(3,"");
            callableStatement.setString(4,"");
            callableStatement.registerOutParameter(4, Types.VARCHAR);
            callableStatement.execute();
            DbOps.getInstance().runQuery("commit;");
            callableStatement.close();
        } catch (SQLException e) {
            logger.error("Problem occurred while executing callable statement: " + callableStatement, e);
        }
    }

Any ideas or advice would be greatly appreciated. I find it extremely weird that I can execute manually via client and command line with no issues :(

  • Does this answer your question? [Cannot delete or update a parent row: a foreign key constraint fails](https://stackoverflow.com/questions/1905470/cannot-delete-or-update-a-parent-row-a-foreign-key-constraint-fails) – seenukarthi Apr 07 '22 at 06:26
  • It doesn't answer the question as I am unable to use SET FOREIGN_KEY_CHECKS=0, besides, the SPs run from client and command line without any problems, but thanks for the advice :D – gangstaShanks Apr 07 '22 at 06:40
  • Using `SET FOREIGN_KEY_CHECKS` isn't the only answer to that question. – Mark Rotteveel Apr 07 '22 at 10:59

0 Answers0