插入失败“ OperationalError:没有这样的列”

时间:2019-04-21 08:10:30

标签: python python-3.x sqlite

我试图用尝试修复的名称和电话创建一个数据库,但是它随时会重放给我:

File "exm0.py", line 14, in <module>
    cursor.execute("""INSERT INTO Employee VALUES({0}, {1})""".format(k, v))
sqlite3.OperationalError: no such column: dani

代码:

from user_names import *
import sqlite3

# user_names.py
names = ["dani", "eric", "dinna", "tamir", "edan", "daniel", "tomer", 
"noa", "shalev", "tom", "shir"]
phones = ["0432", "5415166255", "61467254", "6146758", "5889482"]

connection = sqlite3.connect("")
cursor = connection.cursor()


cursor.execute("""CREATE TABLE Employee(Name text, Phone int)""")
acc = {}

for k, v in zip(names, phones):
    #acc[k] = v
    cursor.execute("""INSERT INTO Employee VALUES({0}, 
{1})""".format(k, v))

3 个答案:

答案 0 :(得分:0)

请勿进行字符串格式化,请使用带占位符的预备语句。

flow-typed

您甚至不需要循环,可以使用 declare export type Store<S, A, D = Dispatch<A>> = { // rewrite MiddlewareAPI members in order to get nicer error messages (intersections produce long messages) dispatch: D, getState(): S, subscribe(listener: () => void): () => void, replaceReducer(nextReducer: Reducer<S, A>): void, }; 方法进行迭代:

for k, v in zip(names, phones):
    #acc[k] = v
    cursor.execute("INSERT INTO Employee VALUES(?, ?)", (k, v))

答案 1 :(得分:0)

我不熟悉您所使用的准备好的语句的样式。另外,最佳实践是始终指定插入目标的列名。试试这个版本:

for k, v in zip(names, phones):
    #acc[k] = v
    cursor.execute("INSERT INTO Employee (Name, Phone) VALUES(?,?)", (k, v))

答案 2 :(得分:0)

您正在将值格式化为语句的文本而不引用它们。因此,数据库将它们解释为列名,从而因您看到的错误而失败。相反,您可以只传递参数数组作为execute函数的第二个参数,并让驱动程序库为您完成繁重的工作:

cursor.execute("INSERT INTO Employee VALUES(?, ?)", [k, v])