我一直得到一个sqlite3.OperationalError:在“;”附近,无法找出原因......
我做错了什么?我试图从员工元组列表中将记录插入数据库。
已阅读其他类似错误但与此不完全相同。
connection = sqlite3.connect("company.db")
cursor = connection.cursor()
cursor.execute("""DROP TABLE employee;""")
staff_data = [ ("William", "Shakespeare", "m", "19611025"),
("Frank", "Schiller", "m", "19550817"), ("Jane", "Wall", "f", "1989-03-14")]
# Define an SQL command
sql_command = """
CREATE TABLE employee (
staff_number INTEGER PRIMARY KEY,
fname VARCHAR(20),
lname VARCHAR(30),
gender CHAR(1),
joining DATE,
birth_date DATE);
"""
# Execute command
cursor.execute(sql_command)
# Insert commands
sql_command = """ INSERT INTO employee (staff_number, fname, lname, gender,
birth_date) VALUES (NULL, "William", "Shakespeare", "m", "1961-10-25");"""
cursor.execute(sql_command)
print(sql_command)
for p in staff_data:
format_str = """ INSERT INTO employee (staff_number, fname, lname, gender, birth_date) VALUES (NULL, "{first}", "{last}", "{gendera}", "{birthdate}"); """
sql_command = format_str.format(first=p[0], last=p[1], gendera=p[2], birthdate=p[3])
print(sql_command)
cursor.execute(sql_command)
# DONT FORGET THIS TO SAVE CHANGES
connection.commit()
connection.close()
这是错误消息:
INSERT INTO employee (staff_number, fname, lname, gender,
birth_date) VALUES (NULL, "William", "Shakespeare", "m", "1961-10-25");
INSERT INTO employee (staff_number, fname, lname, gender, birth_date) VALUES (NULL, "Jane", "Wall", "f", "1989-03-14");
Traceback (most recent call last):
File "sqliteuse0.py", line 53, in <module>
cursor.execute(sql_command)
sqlite3.OperationalError: near ";": syntax error
答案 0 :(得分:1)
format_str = """ INSERT INTO employee (staff_number, fname, lname, gender, birth_date) VALUES (NULL, "{first}", "{last}", "{gendera}", "{birthdate}"); """
那不是分号(;
)。它是U+037E GREEK QUESTION MARK(;
)。
用分号代替,然后重试。
答案 1 :(得分:0)
我使用difflib.ndiff来比较键入的字符串和格式化生成的字符串,并且表示format_str缺少;。我删除并重新输入了它,它解决了这个问题。我相信这是因为直接从带有示例代码的pdf中复制。
问题已解决