1

I have been having some issues trying to create (or select) from tables where the name is dependant on the variable I am giving it.

E.g below is an example of a code I tried that didn't work, where 'Hey' = the name of the table (which exists in the database) that I am trying to select through the variable 'j'.

j = 'Hey'
rows = conn.execute("SELECT * from ?", (j,)).fetchall()
print(rows)

Does anyone have a solution for this? Thanks in advance.

MathiasRa
  • 825
  • 2
  • 12
  • 24

1 Answers1

0

The ? is meant for bound parameters, and unfortunately, table names won't work in this manner. However, this will, but be careful of SQL injection:

j = 'Hey'
rows = conn.execute("SELECT * from {table_name}".format(table_name=j)).fetchall()
print(rows)

Unfortunately, you can't bind it to a T-SQL variable name either, as you're just passing the problem downstream to a T-SQL EXEC command, as outlined here: Table name as variable Please also note this is due to the design of SQL Server and T-SQL, not pyodbc.

Good luck!

FlipperPA
  • 13,607
  • 4
  • 39
  • 71