我正在尝试使用python((3.5)pymssql)脚本遍历mssql数据库中的表我连接后使用以下内容:
table = ("Accounts")
cursor.execute("SELECT TOP 1 * FROM %s",table)
if %s is replaced by a string, say 'Accounts' it works,
cursor.execute("SELECT TOP 1 * FROM Accounts")
当我使用表时,它失败并出现以下错误:
_mssql.MSSQLDatabaseException:(102,b“语法不正确 'Accounts'.DB-Lib错误消息20018
pymssql显示
cursor.execute("select 'hello' where 1 =%d", 1) as correct
如果可以,请帮忙,我有点困惑的应该是一个简单的问题。
最诚挚的问候Richard C
答案 0 :(得分:0)
看起来python创建了参数,所以这应该有效
import pymssql
conn = pymssql.connect(".", "sa", "password", "AdventureWorks2014")
cursor = conn.cursor()
table = ("AWBuildVersion")
cursor.execute("declare @stmt nvarchar(400);set @stmt = 'select top 1 * from ' + %s;exec sp_executesql @stmt", table)
row = cursor.fetchone()
while row:
print("ID=%d, Name=%s" % (row[0], row[1]))
row = cursor.fetchone()
conn.close()