且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

你如何通过 Java 在 SQLite 中强制执行外键约束?

更新时间:2023-12-01 14:30:10

当您查看 SQLite 外键支持页面时 我会这样解释

When you look at the SQLite Foreign Key Support page I would interpret that

  1. SQLlite 必须使用外键支持编译
  2. 您仍然需要为每次与 PRAGMA 的连接打开它
  3. 您必须在创建表时将外键定义为约束

广告 1) 引自 此处:

如果命令PRAGMA foreign_keys"没有返回数据,而是一行包含0"或1",那么你使用的SQLite版本不支持外键(要么是因为它比3.6.19 或者因为它是用定义的 SQLITE_OMIT_FOREIGN_KEY 或 SQLITE_OMIT_TRIGGER 编译的).

If the command "PRAGMA foreign_keys" returns no data instead of a single row containing "0" or "1", then the version of SQLite you are using does not support foreign keys (either because it is older than 3.6.19 or because it was compiled with SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER defined).

PRAGMA foreign_keys; 的结果是什么?

更新:从您的评论中我看到您使用的是 3.6.14.2,这意味着您的版本不支持外键约束!所以你必须更新 SQLite,如果可能的话!

广告 2) 您的第一个代码片段将 PRAGMA 作为语句执行,我认为这行不通.根据您的评论,第三个片段不起作用:SQLite 驱动程序将整个字符串解释为数据库的位置,而不是将foreign keys=true"部分作为连接设置".所以只有第二个片段有效.

Ad 2) Your first code snippet executes the PRAGMA as statement, I don't think this will work. The third snipped didn't work based on your comment: the SQLite driver interprets the whole string as the location of the database, instead of taking the "foreign keys=true" part as connection settings". So only the second snippet will work.

广告 3) 您是否创建了支持外键的表?引用自此处:

Ad 3) Did you create the table with foreign key support? Quoted from here:

CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);
CREATE TABLE track(
  trackid     INTEGER, 
  trackname   TEXT, 
  trackartist INTEGER,
  FOREIGN KEY(trackartist) REFERENCES artist(artistid)
);