簡體   English   中英

sqlite3將主鍵數據從一個表插入到另一個表

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM