简体   繁体   English

在 sqlite3 中为 python 插入外键

[英]Inserting with Foreign Key in sqlite3 for python

I have a database called soccer.db with two tables team and game我有一个名为soccer.db的数据库,其中包含两个表teamgame

I used DB Browser to create the database.我使用 DB Browser 创建数据库。 My sqlite3 version is 3.30.0.我的sqlite3版本是 3.30.0。 I also confirmed that the foreign keys pragma is enabled/checked.我还确认启用/检查了外键编译指示。

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")
);

Now, I am trying to insert weekly game information into the game database using sqlite3 in a jupyter notebook using the following code.现在,我正在尝试使用以下代码在 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()

When I try to run the code, I get the following error.当我尝试运行代码时,出现以下错误。 I confirmed that the first insert statement worked, so I assume that the error is referring to the second insert statement.我确认第一个插入语句有效,所以我假设错误是指第二个插入语句。

SyntaxError: invalid syntax

What am I doing wrong?我究竟做错了什么?

You should use the lastrowid of the cursor, as in:您应该使用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()

If, on the other hand, you'd like to use an exiting team, you can do the following:另一方面,如果您想使用现有团队,您可以执行以下操作:

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