SQLite会让你在一个事务中放置多个查询,但是为什么当1对另一个有fK_relation时它会发生什么?

时间:2012-12-18 16:06:34

标签: transactions sqlite

我有2个想要执行的查询。

delete from song where ast_id = 1;
delete from artist where ast_id = 1;

与2有关系.1有一个引用另一个的FK。

我在想,查询会一起执行,但我想如果按照正确的顺序执行,会删除艺术家的歌曲,然后删除艺术家本身的歌曲。事实并非如此。

我最终通过将其分成2个交易来解决它,但有没有办法让它只保持1个?

我正在做一些事情:

string query("delete from song where ast_id = 1; delete from artist where ast_id = 1;");
sqlite3_exec(db, query.c_str(),...);

可以在1个交易中完成,例如上面的??

1 个答案:

答案 0 :(得分:2)

如上所述,一种方法是启动事务(与命令不同),添加查询和提交。

(注意这是伪代码,我不确定你正在使用什么平台)

sqlite3_exec(db, "begin;");
sqlite3_exec(db, "delete from song where ast_id = 1;");
sqlite3_exec(db, "delete from artist where ast_id = 1;");
sqlite3_exec(db, "commit;");

但使用外键的方法是确保首先启用外键。

您可以检查它们是否已启用:

PRAGMA foreign_keys;

或者只需打开它们:

PRAGMA foreign_keys = ON;

对于您的歌曲表,您的参考必须正确形成,您必须说明您要删除的内容:

Create Table Song
(
  Song_Id Integer Primary Key,
  ...
  Ast_Id Integer,
  Foreign Key (Ast_Id) References Artist(Ast_Id) ON DELETE CASCADE
);

然后,只需删除艺术家,然后将播放歌曲。