gpt4 book ai didi

java + SQLite 项目。外键 "On Update"未更新

转载 作者:行者123 更新时间:2023-12-01 16:57:50 24 4
gpt4 key购买 nike

我正在使用 SQLite 版本 3.30.1 和 DB Browser for SQLite 制作 javafx(intelliJ with java jdk 11)应用程序。我有一个名为“ hive ”的表,每个 hive 都可能有疾病(存储在“疾病”表中)。这是我的“ hive ”表:

CREATE TABLE "beehives" (
"number" INTEGER NOT NULL,
"id_apiary" INTEGER NOT NULL DEFAULT -2,
"date" DATE,
"type" TEXT,
"favorite" BOOLEAN DEFAULT 'false',
PRIMARY KEY("number","id_apiary"),
FOREIGN KEY("id_apiary") REFERENCES "apiaries"("id") ON DELETE SET NULL
);

这是我的“疾病”表:

CREATE TABLE "diseases" (
"id" INTEGER NOT NULL,
"id_beehive" INTEGER NOT NULL,
"id_apiary" INTEGER NOT NULL,
"disease" TEXT NOT NULL,
"treatment" TEXT NOT NULL,
"start_treat_date" DATE NOT NULL,
"end_treat_date" DATE,
PRIMARY KEY("id"),
FOREIGN KEY("id_beehive","id_apiary") REFERENCES "beehives"("number","id_apiary") ON UPDATE CASCADE
);

这是我的“养蜂场”表,以防您需要:

CREATE TABLE "apiaries" (
"id" INTEGER NOT NULL,
"name" TEXT NOT NULL,
"address" TEXT,
PRIMARY KEY("id")
);

一切正常,但是当我更新 hive 时(例如,当我更新“数字”,这是 hive 表中的主键)时,疾病不会更新数字。结果是,由于 hive 正确地改变了他的“号码”,疾病在某种程度上被断开了,但疾病并没有更新它。没有错误消息。我调用更新的java方法是:

    public void updateBeehiveInDB(Beehives newBeehive,Beehives oldBeehive){        

try {

s = "UPDATE beehives SET number=?, id_apiary=?, date=?, type=?, favorite=? WHERE number=? and id_apiary=? ";
preparedStatement = connection.prepareStatement(s);
preparedStatement.setInt(1, newBeehive.getNumber());
preparedStatement.setInt(2, newBeehive.getId_apiary());
preparedStatement.setDate(3, newBeehive.getDate());
preparedStatement.setString(4, newBeehive.getType());
preparedStatement.setBoolean(5, newBeehive.isFavorite());
preparedStatement.setInt(6, oldBeehive.getNumber());
preparedStatement.setInt(7,oldBeehive.getId_apiary());

int i = preparedStatement.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

我尝试按照 SQLite 文档 here 检查外键是否“打开” ,但是我的英语不够好,我正在使用DB Manager。所以不知道如何检查它是否打开,或者如何手动打开它。

当我更新 hive 表上的“number”时,我该怎么做才能更新疾病“id_beehives”?

最佳答案

问题是我正在使用复合外键,即使我在这个新项目中尚未使用它们,我也需要在其他表上正确实现它。很难找到问题,因为 intellij 通常会显示所有 SQL 错误消息,但在本例中,它没有显示任何内容。但是当我尝试在数据库浏览器中手动执行 SQL 语句时,我收到一条错误消息并能够修复它。

还必须在连接上激活外键:

   public Connection openConnection() {

try {

String dbPath = "jdbc:sqlite:resources/db/datab.db";
Class.forName("org.sqlite.JDBC");

SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
connection = DriverManager.getConnection(dbPath,config.toProperties());

return connection;

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

关于java + SQLite 项目。外键 "On Update"未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61558162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com