32

How do I use prepared statement for inserting MULTIPLE records in SQlite using Python / Django?

Mahendra Liya
  • 12,912
  • 14
  • 88
  • 114

2 Answers2

53

Official Python library documentation: 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)
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
Amber
  • 507,862
  • 82
  • 626
  • 550
  • 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 05:15
  • 2
    @mahendraliya which is why `.executemany()` exists: http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany – Amber Apr 11 '11 at 05: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 05:30
  • @mahendraliya - added an example of `executemany` usage, as requested. – Amber Apr 11 '11 at 06:49
  • @Amber: your code worked very well for me.. BUT I get errors when I try to run executemany() for values having non-english characters.. this worked earlier with executescript().. I don't know why it fails with executemany()..? Do you have any idea? – Mahendra Liya Apr 12 '11 at 07:33
  • I don't know how to check for the encoding, can you please suggest how can I test it? The exact error obtained is : "sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless you use a text_factory that can interpret 8-bit bytestrings (like text_factory = str). It is highly recommended that you instead just switch your application to Unicode strings." – Mahendra Liya Apr 15 '11 at 06:55
  • I solved the error by using con.text_factory = str; Thanks for your all help and coming back again to the question – Mahendra Liya Apr 15 '11 at 09:59
9

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))
flacs
  • 3,913
  • 4
  • 19
  • 20