Passing table name as a parameter in pyodbc

纵饮孤独 提交于 2019-12-05 06:32:59

Since you are using pyodbc, I assume you are not calling a SPROC. I recommend building your SQL string in python and then passing it to SQL to execute.

import pyodbc
dbconn = pyodbc.connect(ConnectionString)
c = dbconn.cursor()

j = 'table1' #where table1 is entered, retreived, etc
query = "Select * from %s" % j
c.execute(query)
result = c.fetchall()
print 'Done'

You can't have variable as a table name SQL Server. You need to use dynamic SQL for that to work.

Look here for how to deal with dynamic table names. http://www.sommarskog.se/dynamic_sql.html#objectnames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!