SQLiteexecutemany 的问题
我在下面的代码中找不到我的错误。 运行时,会出现以下行的类型错误: cur.executemany(sql % itr.next()) => '函数恰好需要 2 个参数(给定 1 个参数),
import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table IF NOT EXISTS fred (dat)")
def newSave(className, fields, objData):
sets = []
itr = iter(objData)
if len(fields) == 1:
sets.append( ':' + fields[0])
else:
for name in fields:
sets.append( ':' + name)
if len(sets)== 1:
colNames = sets[0]
else:
colNames = ', '.join(sets)
sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
print itr.next()
cur.executemany(sql % itr.next())
con.commit()
if __name__=='__main__':
newSave('fred', ['dat'], [{'dat':1}, {'dat':2}, { 'dat':3}, {'dat':4}])
我很感激您的想法。
I can't find my error in the following code. When it is run a type error is given for line: cur.executemany(sql % itr.next()) => 'function takes exactly 2 arguments (1 given),
import sqlite3
con = sqlite3.connect('test.sqlite')
cur = con.cursor()
cur.execute("create table IF NOT EXISTS fred (dat)")
def newSave(className, fields, objData):
sets = []
itr = iter(objData)
if len(fields) == 1:
sets.append( ':' + fields[0])
else:
for name in fields:
sets.append( ':' + name)
if len(sets)== 1:
colNames = sets[0]
else:
colNames = ', '.join(sets)
sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
print itr.next()
cur.executemany(sql % itr.next())
con.commit()
if __name__=='__main__':
newSave('fred', ['dat'], [{'dat':1}, {'dat':2}, { 'dat':3}, {'dat':4}])
I would appreciate your thoughts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如它所说,executemany 有两个参数。 您应该传递 sql 和值并让数据库适配器引用它们,而不是自己用 % 插入字符串值。
Like it says, executemany takes two arguments. Instead of interpolating the string values yourself with the %, you should pass both the sql and the values and let the db adapter quote them.
请参阅sqlite3 文档。 正如您将看到的,
Cursor.executemany
方法需要两个参数。 也许您误以为它是只需要一个的Connection.executemany
方法?See the sqlite3 documentation. As you'll see, the
Cursor.executemany
method expects two parameters. Perhaps you mistook it for theConnection.executemany
method which only takes one?谢谢大家的答案。 经过几天的推挤和戳戳并在您的指导下进行以下工作。 我对我的问题想得太多而感到内疚。 不需要 iter() 转换。 objData 变量是一个列表并且已经是一个可迭代的! 这是代码不起作用的原因之一。
Thank you all for your answers. After pushing and poking for several days and using your guidance the following works. I'm guilty of overthinking my problem. Didn't need an iter() conversion. The objData variable is a list and already an iterable! This was one of the reasons the code didn't work.
也许你的意思是:
还请注意,打印语句消耗迭代器中的一项。
Perhaps you meant:
also note that the print statement consumes one item from the iterator.