python – SQLite executemany的问题

我在以下代码中找不到我的错误.当它运行时,为行提供了类型错误: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}])

我很感激你的想法.

最佳答案 就像它说的那样,executemany有两个参数.不要使用%自己插入字符串值,而应该传递sql和值,并让db适配器引用它们.

sql = " '''insert into %s (%s) values(%%s)'''," % (className, colNames)
cur.executemany(sql, itr.next())
点赞