Zach Cleary
Zach Cleary

Reputation: 552

MSSQL data insertion with Python and pypyodbc - Params must be in a list, tuple

I'm attempting to write (I can read fine) values to a MSSQL instance. My code resembles:

import pypyodbc
lst = ['val1', 'val2', 'val3']
connection = pypyodbc.connect(...)
cursor = connection.cursor()
cursor.executemany("INSERT INTO table (a, b, c)VALUES(?,?,?)", lst)

This returns: Params must be in a list, tuple. I've read similar posts which suggest trying lst = list(['val1, 'val2', val3']) But this returns: list() takes at most 1 argument (3 given) I've also tried variations of cursor.execute(), but same problems.

Upvotes: 1

Views: 1533

Answers (1)

randomir
randomir

Reputation: 18697

Note the difference between cursor.execute:

.execute ( operation [, parameters ])

Parameters may be provided as sequence or mapping and will be bound to variables in the operation.

and cursor.executemany:

.executemany ( operation , seq_of_parameters )

Prepare a database operation (query or command) and then execute it against all parameter sequences or mappings found in the sequence seq_of_parameters .

So, if you are executing your query for only one set of values, call it like this:

values = ['val1', 'val2', 'val3']
cursor.executemany("INSERT INTO table (a, b, c) VALUES (?,?,?)", [values])

Or, for multiple sets of values:

values1 = ['val1', 'val2', 'val3']
values2 = ['val3', 'val2', 'val1']
cursor.executemany("INSERT INTO table (a, b, c) VALUES (?,?,?)", [values1, values2])

Upvotes: 2

Related Questions