How do I use prepared statement for inserting MULTIPLE records in SQlite using Python / Django?
http://docs.python.org/library/sqlite3.html#cursor-objects
Python's SQLite libraries don't have prepared statement objects, but they do allow you to use parameterized queries, and to provide more than one set of parameters.
Edit: An example of executemany
as requested:
values_to_insert = [(1,"foo"), (2, "bar"), (3, "baz")]
cursor.executemany("""
INSERT INTO some_table ('item_num', 'item_name')
VALUES (?, ?)""", values_to_insert)
-
1@Amber: thank you for your answer. I had missed one important point i.e. it was insertion of MULTIPLE records.. "execute()" allows only one query to be execute.. so won't work for me :) – Mahendra Liya Apr 11 '11 at 5:15
-
2@mahendraliya which is why
.executemany()
exists: docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany – Amber Apr 11 '11 at 5:19 -
@Amber: i went through executemany() as well but sorry to say I am quite new to both python and sqlite. My doubt is like if I have, say a list of filenames which I have prepared by appending values inside a list object, then how can I use it with executeMany.. is it like simply passing the list object (say fileList) to executemany()?.. Any code snippet would be really appreciated.. thanks. – Mahendra Liya Apr 11 '11 at 5:30
-
-
@Amber: thank you.. will try it out and post comment here post lunch.. will accept the answer if it works.. :) – Mahendra Liya Apr 11 '11 at 7:32
You can use executemany() and pass an iterator object, e.g. to insert 100 integers and their squares:
def my_iter(x):
for i in range(x):
yield i, i*i
cursor.executemany("INSERT INTO my_table VALUES (?, ?)", my_iter(100))
If you are trying to insert just one row as with a PreparedStatement,
cursor.execute("""INSERT INTO table_name ('column1', 'column2') VALUES (?, ?)""", ("value1", "value2"))
should work as well. Values are being passed in as python tuples.
-
3The OP asked about inserting multiple records/rows, not a single row, so I don't see how this answers the question. – Moot Mar 2 '17 at 1:50