Inserting list of strings using executemany() - convert to tuple?

779 views
Skip to first unread message

victo...@gmail.com

unread,
Oct 31, 2013, 6:22:32 PM10/31/13
to python...@googlegroups.com
Hi,

My understanding is that executemany() will only take a tuple as parameters.

So if you have a table like this:

    cur.execute('''CREATE TABLE processed_files
                    (filename text)''')

And you have a list like this:

    processed_files = ['file1.txt', 'file2.txt']

You won't be able to use executemany() directly, as it's a list of strings, whereas executemany() is expecting each item to be a tuple:

    cur.executemany("INSERT INTO processed_files VALUES (?)", processed_files)

What is the recommended way of getting this list into Sqlite3? Is there an concise and idiomatic way to wrap the elements of the list in a tuple for this task? Or another way of getting executemany() to accept the list?

Cheers,
Victor

Roger Binns

unread,
Nov 1, 2013, 1:51:15 PM11/1/13
to python...@googlegroups.com
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 31/10/13 15:22, victo...@gmail.com wrote:
> My understanding is that executemany() will only take a tuple as
> parameters.

For pysqlite, it takes a sequence of sequences. The outer sequence is
what each invocation of executemany iterates on, while each inside
sequence is what is used for that execute. Like this conceptually:

def executemany(query, rows):
for row in rows:
cursor.execute(query, row)

> processed_files = ['file1.txt', 'file2.txt']

processed_files = [ ['file1.txt'], ['file2.txt'] ]

Roger

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.12 (GNU/Linux)

iEYEARECAAYFAlJz6hMACgkQmOOfHg372QR1qACgpKEcno0i61axAirF9O/qNifd
NRoAn0mHhBG7Cf0jJYbiy2rG42i7siZa
=1pKo
-----END PGP SIGNATURE-----
Reply all
Reply to author
Forward
0 new messages