![](/img/trans.png)
[英]sqlite3 in Python: Update a column in one table through a column from another table when the primary key is the same
[英]sqlite3 inserting primary key data from one table into another
我有三個表:書籍,章節,概念。
我希望book_id列在books和Chapters表中是相同的。
我在books表中插入了數據,然后在chapters表中插入了數據,但是Chapters表中的book_id列為空。
如何使這些表具有關聯性?
book_id integer,
title text,
PRIMARY KEY (book_id)
chapter_id integer,
chapter text,
book_id integer,
PRIMARY KEY (chapter_id),
FOREIGN KEY (book_id) REFERENCES books (book_id))'''
concepts_id integer,
concept text,
definition text,
chapter_id integer,
PRIMARY KEY (concepts_id),
FOREIGN KEY (chapter_id) REFERENCES chapters (chapter_id)
cur.execute("INSERT INTO books (title) VALUES ('Intro to Econ.')")
cur.execute("INSERT INTO chapters (chapter) VALUES (1)")
在這里,外鍵的概念可能會有一些誤解。
外鍵是對表另一行的引用 。 雖然主鍵將自動索引,但外鍵不會。 您必須自己插入外鍵; 畢竟,您是在定義關系。
為了實現所需的功能,您需要從第一個查詢中獲取插入的書籍ID,然后手動插入檢索到的值。 可以使用SQLite的last_insert_rowid()
函數來實現。 然后,您將從游標中獲取結果。 這是如何在Python中完成此操作的示例:
#First, we add the SELECT last_insert_rowid() into the query; this is an SQLite function so it goes in the query not in the Python code.
cur.execute("INSERT INTO books (title) VALUES ('Intro to Econ.'); SELECT last_insert_rowid();")
#Get the first column of the first row; in our case, only one column is actually returned anyway.
book_id = cur.fetchone()[0]
#As you can see, we are now inserting the book_id ourselves. Foreign Keys do not auto index, so we need to relate the tables ourselves.
cur.execute("INSERT INTO chapters (chapter, book_id) VALUES (1, " + str(book_id) + ")")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.