【发布时间】:2021-01-26 00:31:28
【问题描述】:
我收到了一个凌乱的 Excel 文件,我正试图将其转移到整理好的 SQL 表中。我正在构建一个 Python 程序来进行传输。有一个名称列表,其中一些是重复的。我已经将包含所有名称的列放入元组列表中,例如:
[(John Christopher, ), (Elizabeth Smith, ), (etc, )]
我已经建立了一个名为 Players 的 SQL 表,并有一个名为“id”的空列。我正在尝试遍历此列表并为表中的每个玩家分配一个唯一的 id,然后还删除我表中的重复名称。
但我不断收到此错误:
cursor.execute("UPDATE Players SET id = "+str(id)+" WHERE name = "+str(item[0]))
sqlite3.OperationalError: near "Christopher": syntax error
我的问题是什么?
代码如下:
import sqlite3
player_list_start = cursor.execute("SELECT name FROM Players")
saved_list = player_list_start.fetchall()
# number id should start on
id = 1
# list of players to keep track if they are already in the table
names = []
for item in saved_list:
if item[0] not in names:
cursor.execute("UPDATE Players SET id = "+str(id)+" WHERE name = "+str(item[0]))
connection.commit()
names.append(item[0])
id += 1
else:
cursor.execute("DELETE FROM Players WHERE name = "+str(item[0])+" AND id = NULL")
connection.commit()
【问题讨论】:
-
真的需要一个最小的例子 - 你能硬编码
saved_list的值并将创建数据库和光标添加到你的代码中吗? -
您面临的错误来自 SQL 本身的语法错误。您需要做的是打印出您正在生成的 SQL 语句,并查看是否有任何错误。尝试将代码粘贴到 SQL 终端中,看看会发生什么。
-
试试这个:
cursor.execute("UPDATE Players SET id = ? WHERE name = ?", (id, item[0])) -
如果您的 SQLite 版本支持它,您可以使用
row_number解决方案一次性完成所有操作