how to insert multiple rows into sqllite3 database

209 Views Asked by At

I am trying to select rows and fetch them from the DB table and then insert them into a list so I can insert all of the rows at once into the database, but I got an error.

def paid_or_returned_buyingchecks(self):

    date = datetime.now()
    now = date.strftime('%Y-%m-%d')
    self.tenlistchecks=[]

    self.con = sqlite3.connect('car dealership.db')
    self.cursorObj = self.con.cursor()

    self.dashboard_buying_checks_dates = self.cursorObj.execute("select id, paymentdate , paymentvalue, car ,sellername from cars_buying_checks where nexttendays=?",(now,))
    self.dashboard_buying_checks_dates_output = self.cursorObj.fetchall()
    self.tenlistchecks.append(self.dashboard_buying_checks_dates_output)
    print(self.tenlistchecks)
    
    self.dashboard_buying_checks_dates = self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",[self.tenlistchecks])

    self.con.commit()

but I got an error : [[(120, '21-08-2022', '1112', 'Alfa Romeo', 'james'), (122, '21-08-2022', '465', 'Buick', 'daniel '), (123, '21-08-2022', '789', 'Buick', 'daniel ')]] self.dashboard_buying_checks_dates = self.cursorObj.executemany( sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 1 supplied.

1

There are 1 best solutions below

4
PChemGuy On

self.cursorObj.fetchall() returns a list of tuples, which is what you need to feed to executemany, so

self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",self.tenlistchecks)

not

self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",[self.tenlistchecks])