Home > Mobile >  Python sqlite3 error -executemany function
Python sqlite3 error -executemany function

Time:04-18

I am importing data from text file,

1, A1, chicago.

2, B1, NY.

3, K2, LA.

d=open('file.txt','r')
data=d.readlines()
data1=[]
for items in data:
    data1=items.split()
    #print(data1)
    stmt = "INSERT INTO Student1 VALUES (?,?,?)"
    cu.executemany(stmt, data1)```


I am getting this error.
cu.executemany(stmt, data1)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 2 supplied.

CodePudding user response:

Following these instructions, I tried to include:

´´´ cu.executemany(stmt, data1,[d]) ´´´

https://techoverflow.net/2019/10/14/how-to-fix-sqlite3-python-incorrect-number-of-bindings-supplied-the-current-statement-uses-1-supplied/

CodePudding user response:

executemany() this function needs second parameter as list of tuples in python. data1 variable in your code is list without tuples. you can use something like following.

import sqlite3
d=open('file.txt','r')
data=d.readlines()
data1=[]
data1_in_list_of_tuple = []
for items in data:
    data1=items.split()
    data1_in_list_of_tuple.append(tuple(data1))
stmt = "INSERT INTO Student1 VALUES (?,?,?)"
cu.executemany(stmt, data1_in_list_of_tuple)

CodePudding user response:

To use "executemany" you need to pass list of tuples:

conn = sqlite3.connect('test.db')
cu = conn.cursor()
d = open('file.txt', 'r')
data = d.readlines()
data1 = []
for items in data:
    data1  = [items.split()]
stmt = "INSERT INTO Student1 VALUES (?,?,?,?)"
cu.executemany(stmt, data1)
conn.commit()

Use executemany to insert list of rows. Or change to "execute"

for items in data:
    data1=items.split()
    #print(data1)
    stmt = "INSERT INTO Student1 VALUES (?,?,?)"
    cu.execute(stmt, data1)
  • Related