Foreign key isn't being enforced

2019-01-27 18:56发布

Why is the following foreign key constraint (although executes fine) not enforced by SQLite? How can I go about enforcing the relationship?

CREATE TABLE User (
    UserID TEXT Unique NOT NULL PRIMARY KEY,
    FirstName TEXT NOT NULL,
    LastName TEXT NOT NULL,
    Username TEXT NOT NULL,
    Password TEXT NOT NULL,
    Email TEXT NOT NULL,
    SignupDate TEXT NOT NULL
)

CREATE TABLE Category (
    CategoryID TEXT Unique NOT NULL PRIMARY KEY,
    UserID TEXT,
    FOREIGN KEY(UserID) REFERENCES User(UserID)
)

2条回答
贼婆χ
2楼-- · 2019-01-27 19:06

As the relevant docs say (in section 2. Enabling Foreign Key Support):

Assuming the library is compiled with foreign key constraints enabled, it must still be enabled by the application at runtime, using the PRAGMA foreign_keys command. For example:

sqlite> PRAGMA foreign_keys = ON;

Foreign key constraints are disabled by default (for backwards compatibility), so must be enabled separately for each database connection separately.

Have you used that PRAGMA in the relevant connection? (Assuming, as the docs say, that sqlite is compiled appropriately, and also a recent-enough version to offer foreign key constraint enforcement, of course).

查看更多
贼婆χ
3楼-- · 2019-01-27 19:07

You can also turn on Foreign Key support via embedding in connectionstring:

foreign keys=True

Example:

"Data Source={DatabaseFullFilePath};Version=3;foreign keys=True;datetimeformat=CurrentCulture"
查看更多
登录 后发表回答