我需要让这个程序在数据库中存储人名和姓氏的值。数据库名为Class,我试图将数据插入其中的表称为Names。 我试图重新排列这几次,并从它的try循环中删除它来尝试诊断问题。提前致谢。我将竭尽所能:)
new_first,new_surname = str(input("Firstname:\t")), str(input("Surname:\t"))
new_name = [new_surname, new_first]
print(new_name)
c.executemany("INSERT INTO Names VALUES (?,?)", new_name)
我不断收到的错误信息是: 提供的绑定数量不正确。当前语句使用2,并且提供了7个。
答案 0 :(得分:1)
executemany()
期望许多项目,顾名思义。
这意味着列表列表或任何类似的数据结构。你只给它一个项目。
new_first, new_surname = str(input("Firstname:\t")), str(input("Surname:\t"))
new_name = [[new_surname, new_first]]
c.executemany("INSERT INTO Names VALUES (?,?)", new_name)
如果您只有一个项目,请使用execute
new_first, new_surname = str(input("Firstname:\t")), str(input("Surname:\t"))
new_name = [new_surname, new_first]
c.execute("INSERT INTO Names VALUES (?,?)", new_name)
答案 1 :(得分:1)
请勿使用cursor.executemany()
,请使用cursor.execute()
:
c.execute("INSERT INTO Names VALUES (?,?)", new_name)
executemany()
应该用于多行数据,但您只有一行。
错误是由executemany()
方法将new_surname
作为一行自行处理引起的,并且由于字符串是可迭代的,因此尝试使用该字符串中的每个字符作为参数。字符串长度为7将为您提供7个参数,这与SQL语句中的2不匹配。
如果你做有很多行,那么每一行必须包含两个参数的最后和第一个名称值:
new_names = [
[new_surname, new_first],
['another surname', 'another first name'],
# ...
]
c.executemany("INSERT INTO Names VALUES (?,?)", new_names)