簡體   English   中英

在 sqlite3 中為 python 插入外鍵

[英]Inserting with Foreign Key in sqlite3 for python

我有一個名為soccer.db的數據庫,其中包含兩個表teamgame

我使用 DB Browser 創建數據庫。 我的sqlite3版本是 3.30.0。 我還確認啟用/檢查了外鍵編譯指示。

CREATE TABLE "team" (
    "id"    INTEGER UNIQUE,
    "opponent_name" TEXT,
    "rank_when played"  INTEGER,
    "date_added"    TEXT,
    PRIMARY KEY("id" AUTOINCREMENT)
);

CREATE TABLE "game" (
    "id"    INTEGER,
    "opponent_id"   INTEGER,
    "goals_for" INTEGER,
    "goals_against" INTEGER,
    "date_added"    TEXT,
    PRIMARY KEY("id" AUTOINCREMENT),
    FOREIGN KEY("opponent_id") REFERENCES "team"("id")
);

現在,我正在嘗試使用以下代碼在 jupyter notebook 中使用 sqlite3 將每周游戲信息插入game數據庫。

conn = sqlite3.connect('soccer.db')
c = conn.cursor()

c.execute('INSERT INTO team (opponent_name, rank_when_played, date_added) VALUES (?,?,?)', ('Manchester_City', 4, '04/22/2018')

c.execute('INSERT INTO game (opponent_id, goals_for, goals_against, date_added) VALUES (?,?,?,?)', ((SELECT id FROM team WHERE opponent_name = 'Machester City'), 3, 2, '04/22/2018')

conn.commit()
c.close()

當我嘗試運行代碼時,出現以下錯誤。 我確認第一個插入語句有效,所以我假設錯誤是指第二個插入語句。

SyntaxError: invalid syntax

我究竟做錯了什么?

您應該使用lastrowid的 lastrowid,如下所示:

c = conn.cursor()

c.execute('INSERT INTO team (opponent_name, rank_when_played, date_added) VALUES (?,?,?)', 
          ('Manchester_City', 4, '04/22/2018'))

c.execute('INSERT INTO game (opponent_id, goals_for, goals_against, date_added) VALUES (?,?,?,?)', 
          (c.lastrowid, 3, 2, '04/22/2018'))
          # ==========

conn.commit()

另一方面,如果您想使用現有團隊,您可以執行以下操作:

c = conn.cursor()
c.execute("Select id from team where opponent_name = ?", ('Manchester_City', ))
res = c.fetchone()
team_id = res[0]

c.execute('INSERT INTO game (opponent_id, goals_for, goals_against, date_added) VALUES (?,?,?,?)', 
          (team_id, 3, 2, '07/23/2018'))
conn.commit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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