lundi 29 décembre 2014

Insert lists in SQLite database

I've got two lists in Python3 to insert in a SQLite database. The following code works but I'm sure there is a better way.



cur.execute("CREATE TABLE my_table (id INT, vegetables TEXT, fruits TEXT)")

ls_vegetables = ['artichoke ', 'broccoli', 'celery']
ls_fruits = ['apple', 'banana', 'coconut']

# Vegetables loop
id = 1
for v in ls_vegetables:
cur.execute("INSERT INTO my_table(ID, vegetables) VALUES (?,?)", (id,v))
id += 1
conn.commit()

# Fruits loop
id=1
for f in ls_fruits:
cur.execute ("UPDATE my_table SET fruits=? WHERE ID=?", (f,id))
id += 1
conn.commit()


Can I have just one loop?


This is the sketch of my table:



+----+------------+---------+
| id | vegetables | fruits |
+====+============+=========+
| 1 | artichoke | apple |
+----+------------+---------+
| 2 | broccoli | banana |
+----+------------+---------+
| 3 | celery | coconut |
+----+------------+---------+

Aucun commentaire:

Enregistrer un commentaire