我有两张表定义如下;从用户表,hospitalId和poliklinikId都引用表relhospol,如果从relhospol删除任何行(如果有任何用户与之相关),我想设置hospitalId和poliklinikId为null,DDL说。当我从SQLite Manager中删除一行时,它会使用户的hospitalId和PoliklinikId为空,但是当我尝试从应用程序级别(Java)中删除一行时,它只从relhospol中删除,它没有设置null(hospitalId,PoliklinikId)是什么遗漏点?
JDBC驱动程序:SQLite-jdbc-3.7.2
CREATE TABLE [USER] (
[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[GROUPID] INTEGER CONSTRAINT [FK_USER_GID] REFERENCES [GROUP]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
[HOSPITALID] INTEGER,
[POLIKLINIKID] INTEGER,
[NAME] VARCHAR(50) NOT NULL,
[LOGINID] VARCHAR(15) NOT NULL,
[EMAIL] VARCHAR(50) NOT NULL,
[PASSWORD] VARCHAR(32) NOT NULL,
CONSTRAINT [FK_USER_RELHOSPOL] FOREIGN KEY([HOSPITALID], [POLIKLINIKID]) REFERENCES [RELHOSPOL]([HOSPITALID], [POLIKLINIKID]) ON DELETE SET NULL ON UPDATE CASCADE);
CREATE UNIQUE INDEX [AS] ON [USER] ([LOGINID]);
CREATE UNIQUE INDEX [AS1] ON [USER] ([EMAIL]));
CREATE TABLE [RELHOSPOL] (
[HOSPITALID] INTEGER CONSTRAINT [FK_RELHOSPOL_HOS] REFERENCES [HOSPITAL]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
[POLIKLINIKID] INTEGER CONSTRAINT [FK_RELHOSPOL_POL] REFERENCES [POLIKLINIK]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT [sqlite_autoindex_RELHOSPOL_1] PRIMARY KEY ([HOSPITALID], [POLIKLINIKID]));
答案 0 :(得分:0)
您无法将NULL设置为主键:
CREATE TABLE [RELHOSPOL] (
[HOSPITALID] INTEGER CONSTRAINT [FK_RELHOSPOL_HOS] REFERENCES [HOSPITAL]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
[POLIKLINIKID] INTEGER CONSTRAINT [FK_RELHOSPOL_POL] REFERENCES [POLIKLINIK]([ID]) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT [sqlite_autoindex_RELHOSPOL_1] PRIMARY KEY ([HOSPITALID], [POLIKLINIKID]));
您是要尝试从哪个表中删除一行?你能发布DELETE SQL吗?
答案 1 :(得分:0)
好的我已经改变了RELHOSPOL的定义如下;当我通过执行DELETE命令从SQL管理器中删除RELHOSPOL中的行时,它会使USER表中的必要行为空。每当我使用下面编写的方法从应用程序中删除一行时,它只从RELHOSPOL中删除行,并且在USER表中没有SET NULL必要的行
CREATE TABLE [RELHOSPOL] (
[ID] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[HOSPITALID] INTEGER,
[POLIKLINIKID] INTEGER);
CREATE UNIQUE INDEX [UNIQUE_RELHOSPOL] ON [RELHOSPOL] ([HOSPITALID], [POLIKLINIKID]);
删除方法是:
public void deletePoliklinikFromHospital(int hospitalId, int poliklinikId) throws SQLException{
String query = "DELETE FROM [RELHOSPOL] WHERE (HOSPITALID = ? AND POLIKLINIKID = ?)";
try {
PreparedStatement statement = db.prepareStatement(query);
statement.setInt(1, hospitalId);
statement.setInt(2, poliklinikId);
statement.executeUpdate();
} catch (SQLException e) {
throw new SQLException(e.getMessage());
}
}
答案 2 :(得分:0)
这只是猜测,但也许您不知道,每次连接数据库时都必须enable foreign key support PRAGMA foreign_keys = ON;
?如果不这样做,您的语句将被解析,但不会被强制执行。这可以解释为什么它来自SQLite Manager。
还应该知道,旧版本的Sqlite(< 3.6.19)将容忍语法,但也不会强制执行任何操作。
作为旁注:
正如@Neuquino写表ON DELETE SET NULL
的{{1}}语句似乎没有意义。