I am tried to pass table name in pyodbc as a parameter to access data from ms sql 2005. I tried to substitute it with ? but it never works. I would be glad to receive any advice on how to accomplish this.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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'
回答2:
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