简体   繁体   English

在pyodbc中将表名作为参数传递

[英]Passing table name as a parameter in pyodbc

I am trying to pass a table name in pyodbc as a parameter to access data from ms sql 2005. I've tried to substitute it with ?我试图在pyodbc中传递一个表名作为参数来访问来自 ms sql 2005 的数据。我试图用? but it never works.但它永远不会奏效。 I would be glad to receive any advice on how to accomplish this.我很高兴收到有关如何完成此任务的任何建议。

Since you are using pyodbc, I assume you are not calling a SPROC.由于您使用的是 pyodbc,我假设您没有调用 SPROC。 I recommend building your SQL string in python and then passing it to SQL to execute.我建议在 python 中构建您的 SQL 字符串,然后将其传递给 SQL 执行。

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.您不能将变量作为表名 SQL 服务器。 You need to use dynamic SQL for that to work.您需要使用动态 SQL才能工作。

Look here for how to deal with dynamic table names.在这里查看如何处理动态表名。 http://www.sommarskog.se/dynamic_sql.html#objectnames http://www.sommarskog.se/dynamic_sql.html#objectnames

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM