1

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.

Zach Cleary
  • 458
  • 1
  • 4
  • 17

1 Answers1

2

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])
Community
  • 1
  • 1
randomir
  • 17,989
  • 1
  • 40
  • 55
  • Thanks, but sadly it now returns: ('HY000', 'The SQL contains 3 parameter markers, but 1 parameters were supplied') – Zach Cleary Jul 27 '17 at 14:29
  • Are you sure you're running the same code you provided in your question? Because there are only 3 parameter placeholders. – randomir Jul 27 '17 at 14:48