我有两张表定义如下;当我通过执行DELETE命令从SQL管理器中删除RELHOSPOL中的行时,它会使USER表中的必要行为空。每当我使用下面编写的方法从应用程序中删除一行时,它只会删除RELHOSPOL中的行,并且不会在USER表中设置必要的行。缺少什么?
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] (
[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());
}
}
答案 0 :(得分:0)
您需要turn on enforcement of foreign keys,默认情况下由于向后兼容性而关闭。这是一个每连接配置选项。将此添加为您在创建Connection
后首先执行的操作之一:
PRAGMA foreign_keys = on;