gpt4 book ai didi

android - 如何在Android上的SQLite数据库中实现 "Inheritance"关系

转载 作者:IT王子 更新时间:2023-10-29 06:21:51 24 4
gpt4 key购买 nike

考虑这个简单的模型:

基本位置表:

+-------------------------------+
| Locations |
+-------------------------------+
|(PK) _id Integer Autoincrement |
| name Text(100) Not null |
| is_in_range Integer |
+-------------------------------+

还有更专门的表,称为 WifiLocation:

+-------------------------------+
| wifi_location |
+-------------------------------+
| ssid Text(0) Not null |
| signal_threshold Real |
|(PK) _id Integer |
+-------------------------------+

我希望此模型将表示继承自 BaseLocationWifiLocation。所以我在 wifi_locations 表的 _id 列上添加了一个 REFERENCES 子句,如下所示:

CREATE TABLE wifi_locations (_id Integer primary key references Locations(_id), ....)

我试图在这些表之间实现 1:1 的关系。

当我想向 wifi_locations 表中插入一行时,我首先将适当的值(Name、IsInRange)插入到 Locations 表中,然后取回 行号。然后我将其余数据 (ssid) 连同作为外键的 rowId 插入到 wifi_locations 表中。

所以插入 Location 表是有效的,我得到了一个 Id,但是当我尝试使用这个 Id 并将它插入到 wifi_locations 表时,我得到了一个 SQL Constraint violation 错误。没有关于到底出了什么问题的更多详细信息。

我的模式有什么问题吗?有没有更好的方法来实现这样的建模?

编辑:

确切的错误:

06-16 15:56:42.846: E/Database(2038):
android.database.sqlite.SQLiteConstraintException:
error code 19: constraint failed

最佳答案

您应该在第二个表中创建 FOREIGN KEY,并引用 Locations 表中的 PRIMARY KEY。在 SQLite 中,支持 FOREIGN KEYS 但隐式未启用,因此首先您必须启用它们。

final String ENABLE_FOREIGN_KEYS ="PRAGMA foreign_keys=ON";
db.execSQL(ENABLE_FOREIGN_KEYS);

SQLiteOpenHelperonOpen() 方法中。

然后你的 FOREIGN KEY 看起来像这样:

CREATE TABLE wifi_location (
SSID TEXT NOT NULL,
SIGNAL_THRESHOLD REAL,
_id INTEGER,
FOREIGN KEY(_id) REFERENCES Locations(_id)
);

所以这一切都从 SQLite version 3.6.19 开始有效。有关更多信息,请查看 SQLite Foreign Key Support .

关于android - 如何在Android上的SQLite数据库中实现 "Inheritance"关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11065374/

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