1

I've been having trouble with 1 particular query for the past week. I can't find anything online for this specific situation (or atleast I'm not searching the right thing) but surely this is something somebody has done before. I'm generating a new table on each cycle (with an incrementing ID/key column, and 3 columns for my data) so the table name changes, then putting in some data (all integers). The line causing the error is:

cursor.execute(''' INSERT INTO ? (column1, column2, column3) VALUES (?, ?, ?) ''' , tablename, rowData[0], rowData[1], rowData[2])

The error I'm getting is:

('42000', '[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Must declare the table variable "@P1". (1087) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared. (8180)')

I previously tried using the usual python string formatting, with a dictionary '''INSERT INTO %(table)s VALUES %(list0)i, %(list1)i, %(list2)i ''' % {"table":tablename, "list0":list[0], "list1":list[1], "list2":list[2]}) and some variations of the 2 formats but those have resulted in errors too.

Any help would be appreciated.

1
  • is more easy if you use procedures Commented Nov 6, 2019 at 21:59

1 Answer 1

2

You're right in thinking that you should be using a parameterized query, but query parameters can only be used to insert column values, not column/table names. So you need to use a mix of dynamic SQL and query parameterization:

sql = "INSERT INTO [%s] (column1, column2, column3) VALUES (?, ?, ?)" % tablename
cursor.execute(sql, rowData[0], rowData[1], rowData[2])
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, I see. Thank you so much. This is annoyingly close to one of the variations I tried too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.