jdbc中的外键问题 [英] foreign key problem in jdbc

查看:264
本文介绍了jdbc中的外键问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个功能:

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.

现在,我需要通过jbdc填充数据库。所以我使用:
public void Populate_reservations()函数:

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

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.

所以它应该是这样的:

Statement s = conn.createStatement();

  s.execute("SET FOREIGN_KEY_CHECKS=0");

     s.executeUpdate("DELETE FROM flights");
 s.execute("SET FOREIGN_KEY_CHECKS=1");


推荐答案

您可以临时禁用MySQL中的外键检查来执行如果启用了这些检查,则会失败的操作:

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

请注意,这是一个每个连接设置,所以你必须使用相同的 conn object。

Note that this is a per connection setting so you have to do all your stuff using the same conn object.

这篇关于jdbc中的外键问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆