foreign key problem in jdbc
I have two functions:
public void Populate_flights()
public void Populate_reservations()
Fli开发者_运维知识库ght and reservations are two tables.One of the entry i.e flight no. is in the reservation table. So it is a foreign key.
Now, I need to populate the database via jbdc. So I am using: In public void Populate_reservations() function:
Statement s = conn.createStatement();
s.executeUpdate("DELETE FROM reservations");
public void Populate_flights() -:
Statement s = conn.createStatement();
s.executeUpdate("DELETE FROM flights");
So in this way, before populating the database, all my previous entries are removed and no redundant data is there.Since, there is a foreign key in reservation table, I can't delete entries from flight first. I have to remove entries from reservation first. But reservation function is called after flight function.SO how would I make it so that it will delete all the entries.
So it should be like this:
Statement s = conn.createStatement();
s.execute("SET FOREIGN_KEY_CHECKS=0");
s.executeUpdate("DELETE FROM flights");
s.execute("SET FOREIGN_KEY_CHECKS=1");
You can temporary disable foreign key checks in MySQL to perform operations that would fail if these checks were enabled:
// Disable foreign keys check
Statement stmt = conn.createStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=0");
stmt.close();
// Do your stuff
// Enable foreign keys check
Statement stmt = conn.createStatement();
stmt.execute("SET FOREIGN_KEY_CHECKS=1");
stmt.close();
Note that this is a per connection setting so you have to do all your stuff using the same conn
object.
So you want to cascade the foreign key references on delete. You have to set it on the foreign key constraint. First drop the old constraint and then recreate it with the cascade instruction. Assuming that the FK name is fk_flight
, here's an example:
ALTER TABLE reservations
DROP CONSTRAINT fk_flight;
ALTER TABLE reservations
ADD CONSTRAINT fk_flight
FOREIGN KEY (flight_id)
REFERENCES flight(id)
ON DELETE CASCADE;
This way all referenced reservations will be deleted if you delete alone the flight.
Statement s = conn.createStatement();;
s.addBatch("SET FOREIGN_KEY_CHECKS = 0");
s.addBatch("DELETE FROM reservations");
s.addBatch("DELETE FROM flights");
s.addBatch("SET FOREIGN_KEY_CHECKS = 1");
s.executeBatch();
精彩评论