Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

java - foreign key problem in jdbc

I have two functions:

public void Populate_flights()

public void Populate_reservations()

Flight 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");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...