简体   繁体   English

jdbc中的外键问题

[英]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 ie flight no. 航班和预订是两个表格。其中一个条目即航班号。 is in the reservation table. 在预订表中。 So it is a foreign key. 因此,这是一个外键。

Now, I need to populate the database via jbdc. 现在,我需要通过jbdc填充数据库。 So I am using: In public void Populate_reservations() function: 所以我正在使用:在公共void Populate_reservations()函数中:

Statement s = conn.createStatement();

s.executeUpdate("DELETE FROM reservations");

public void Populate_flights() -: 公共无效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: 您可以在MySQL中暂时禁用外键检查,以执行如果启用以下检查将失败的操作:

// 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. 请注意,这是每个连接的设置,因此您必须使用相同的conn对象来完成所有工作。

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: 假设FK名称为fk_flight ,这是一个示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM