1

I have a list called

fullpricelist=[373.97, 381.0, 398.98, 402.98, 404.98, 457.97, 535.99, 550.97, 566.98]

I would like to write this list into a slqlite database column, I found the following code from another question and changed it to my situation.

cursor.executemany("""INSERT INTO cardata (fullprice) VALUES (?)""", 
                   zip(fullpricelist))

My current script is this

for name, name2, image in zip(car_names, car_names2, images):
    cursor.execute(
        "insert into cardata (carname, carmodel, imageurl, location, Fro, T, companyid) values (?, ?, ?, ?, ?, ?, ?)",
        (name.text, name2.text, image.get_attribute('src'), location, pickup_d, return_d, Rental_ID)
    )

But now I am confused how to add these codes together

1 Answer 1

1

In your second piece of code, execute() is called and one specific object is stored in the database each loop iteration. This is slow and inefficient.

for price in fullpricelist:
    cursor.execute("""INSERT INTO cardata (fullprice) VALUES (?)""", price)

executemany() reads from an iterable and adds each element of the iterable to the database as a distinct row. If you add many elements to a database and care about efficiency, you want to use executemany()

cursor.executemany("""INSERT INTO cardata (fullprice) VALUES (?)""", fullpricelist)

If you want to include the other columns in your question, your code will be

cursor.executemany("""INSERT INTO cardata (carname, carmodel, imageurl, location, Fro, T, companyid) values (?, ?, ?, ?, ?, ?, ?)""", 
        [
             [name.text for name in car_names], 
             [name.text for name in car_names2], 
             [image.get_attribute('src') for image in images], 
             [location]*len(car_names), 
             [pickup_d]*len(car_names), 
             [return_d]*len(car_names), 
             [Rental_ID]*len(car_names)
        ]  
    )

This assumes all values for location, pickup_d, return_d and Rental_ID are the same, as you did not provide a list of the values.

Sign up to request clarification or add additional context in comments.

1 Comment

I am getting this error. cursor.executemany("""INSERT INTO cardata (fullprice) VALUES (?)""", fullpricelist) sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 6 supplied

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.