首页 > 解决方案 > 将python连接到sqlite3并一次填充多行

问题描述

这不是打印错误的值r=[bounch of number]并且不知道结果的数量和值是 by 的名称r

conn = sqlite3.connect('/home/cbbi-l2-16/Desktop/karim')
c = conn.cursor()

print ("Opened database successfully")
example = [r,result]

for row in c.executemany("INSERT INTO Entrez (PuId,Abstract) VALUES 
(?,?)",(r,resul)):
    print (row)

conn.commit()
c.close()

它给出错误:

Traceback (most recent call last):
  File "sqlpython.py", line 60, in <module>
    for row in c.executemany("INSERT INTO Entrez (PuId,Abstract) VALUES (?,?)",(r,resul)):
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 5 supplied.

标签: pythonsqlite

解决方案


这不是executemany. 你可以把它想象成一个嵌套for循环,它迭代一个外部容器(代表一个查询),然后迭代代表要解包到查询中的数据的内部容器。

但是,在您的情况下,您只有一个列表,其中可能包含字符串。因此,内部的“for”循环开始解包字符串的字符:

data = ['hello', 'something']

for item in data:
    for subitem in item:
        print(subitem) # this is what it's trying to insert

这是 的实际用例executemany,您要在其中解压缩内部容器中的值:

data = [['hello', 'something'], ['goodbye', 'something_else']]
for item in data:
    for subitem in item:
        print(subitem) # this is what it's trying to insert

只需使用execute.


推荐阅读