简体   繁体   English

在 Python 的 sqlite3 中使用外键

[英]Using foreign keys in sqlite3 for Python

I'm writing a program that creates a sqlite3 database through python. I have one table of Authors (AuthorID, Name) and a second table of books (BookID, Title, AuthorID) I've created these as shown below:我正在编写一个程序,通过 python 创建一个 sqlite3 数据库。我有一个作者表(AuthorID,姓名)和第二个书表(BookID,标题,AuthorID)我创建了这些,如下所示:

Authors = sqlite3.connect('Authors.db')
Authors.execute('''CREATE TABLE Authors
       (AuthorID      INT  PRIMARY KEY, 
       Name           TEXT);''')
Authors.close()


Books = sqlite3.connect('Books.db')
Books.execute('''CREATE TABLE Books
       (BookID            INT  PRIMARY KEY, 
       Title              TEXT,
       AuthorID           INT,
       FOREIGN KEY(AuthorID) REFERENCES Authors(AuthorID));''')
Books.close()

I then go to add a record to each of the tables as shown below:我然后 go 向每个表添加一条记录,如下所示:

Authors = sqlite3.connect('Authors.db') 
Authors.execute("INSERT INTO Authors (AuthorID, Name) \
        VALUES (1, 'Jane Austin')");

Authors.commit()
Authors.close()


Books = sqlite3.connect('Books.db')
Books.execute("INSERT INTO Books (BookID, Title, AuthorID) \
        VALUES (1, 'Emma', 1)");

Books.commit()
Books.close()

The database is correctly updated but I don't think the foreign keys are working correctly because it allows me to remove the Author 'Jane Austin', when there are books associated with it.数据库已正确更新,但我认为外键无法正常工作,因为当有相关书籍时,它允许我删除作者“Jane Austin”。

I've seen some tutorials use this line:我看过一些教程使用这一行:

Books.execute("PRAGMA foreign_keys = 1")

Is this the answer to the problem and if so where do I put this line?这是问题的答案吗?如果是,我应该把这条线放在哪里?

The PRAGMA foreign_keys setting applies to a connection, so you should execute it immediately after calling sqlite3.connect() . PRAGMA foreign_keys设置适用于连接,因此您应该在调用sqlite3.connect()后立即执行它。

Please note that foreign key constraints work only inside the same database;请注意,外键约束只在同一个数据库内起作用; you should put both tables into the same file.你应该把两个表放在同一个文件中。

So to do what you want to do you need to create one database file with 2 tables.因此,要做您想做的事情,您需要创建一个包含 2 个表的数据库文件。

Example:例子:

conn=sqlite3.connect("clientdatabase.db")
conn.execute("PRAGMA foreign_keys = 1")
cur=conn.cursor()

# Create 2 tables if they don't exist: Clients and Work_Done
cur.execute('''CREATE TABLE IF NOT EXISTS Clients
(CID INTEGER PRIMARY KEY,
First_Name  TEXT    NOT NULL,
Last_Name       TEXT,
Business_Name   TEXT,
Phone           TEXT,
Address         TEXT,
City            TEXT,
Notes           TEXT,
Active_Status   TEXT    NOT NULL)''')      

cur.execute('''CREATE TABLE IF NOT EXISTS Work_Done
(ID INTEGER PRIMARY KEY,
Date            TEXT    NOT NULL,
Onsite_Contact  TEXT,
Work_Done       TEXT    NOT NULL,
Parts_Installed TEXT,
Next_Steps      TEXT,
CID             INT,
FOREIGN KEY (CID) REFERENCES CLIENTS (CID))''')
conn.commit()

Note that both tables are in the same database and you add the line after connection and before the cursor object.请注意,两个表都在同一个数据库中,并且您在连接之后和游标对象之前添加了一行。

Hope this helps.希望这可以帮助。

Also note that if there is an active transaction, the PRAGMA foreign_keys does not work.另请注意,如果存在活动事务,则PRAGMA foreign_keys不起作用。 There is no error message if you try to do so but foreign keys will still be turned off.如果您尝试这样做,则不会出现错误消息,但外键仍将被关闭。

If you have problems with foreign keys even after using the pragma, it may be worth an attempt to execute COMMIT once before using it.如果您在使用 pragma 后仍然遇到外键问题,那么在使用之前尝试执行一次COMMIT可能是值得的。

FYI, according to the recent official document , you can use PRAGMA foreign_keys = ON .仅供参考,根据最近的官方文档,您可以使用PRAGMA foreign_keys = ON

connection = sqlite3.connect(DB_FILE)
connection.execute('PRAGMA foreign_keys = ON')
cursor = connection.cursor()
(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM