" ON DELETE CASCADE"使用Python时不起作用

时间:2016-01-07 18:11:35

标签: python sqlite

这里我提供了一个完全可重现的代码,它演示了整个问题。问题在于,当我从" parent"中删除行时表,来自"孩子的相应行"表不会被删除,即使它们具有指定了ON DELETE CASCADE的外键。所以这是代码:

>>> import sqlite3
>>> cnx = sqlite3.connect("mytest.db")
>>> cursor = cnx.cursor()
>>> cnx.execute("BEGIN")
<sqlite3.Cursor object at 0x7f0ab0923490>
>>> cursor.execute("CREATE TABLE test_table (id integer)")
<sqlite3.Cursor object at 0x7f0ab0923420>
>>> cursor.execute("CREATE UNIQUE INDEX id_primary ON test_table(id)")
<sqlite3.Cursor object at 0x7f0ab0923420>
>>> cursor.execute("INSERT INTO test_table (id) VALUES (1),(2),(3)")
<sqlite3.Cursor object at 0x7f0ab0923420>
>>> cursor.execute("CREATE TABLE test_table_2(id_fk integer, txt text,  FOREIGN KEY (id_fk) REFERENCES test_table(id) ON DELETE CASCADE)")
<sqlite3.Cursor object at 0x7f0ab0923420>
>>> cursor.execute("INSERT INTO test_table_2 (id_fk, txt) VALUES (1,\"one\"),(2,\"two\"),(3,\"three\")")
<sqlite3.Cursor object at 0x7f0ab0923420>
>>> res = cursor.execute("SELECT * FROM test_table_2")
>>> res
<sqlite3.Cursor object at 0x7f0ab0923420>
>>> for r in res:
...     print(r)
...
(1, 'one')
(2, 'two')
(3, 'three')
>>> cursor.execute("PRAGMA foreign_keys = ON")
<sqlite3.Cursor object at 0x7f0ab0923420>
>>> cursor.execute("DELETE FROM test_table WHERE id = 1")
<sqlite3.Cursor object at 0x7f0ab0923420>
>>> res = cursor.execute("SELECT * FROM test_table_2")
>>> for r in res:
...     print(r)
...
(1, 'one')
(2, 'two')
(3, 'three')

正如您所看到的,我甚至在PRAGMA foreign_keys = ON之前明确地运行DELETE,但它没有帮助。顺便说一句,如果我在sqlite3>提示符下运行这些命令,那么一切正常。所以,整个问题在于Python库。

1 个答案:

答案 0 :(得分:3)

FOREIGN_KEYS pragma是事务内部的无操作。

  

此pragma是交易中的无操作;只有在没有挂起的BEGIN或SAVEPOINT时才能启用或禁用外键约束实施。