在调用MS SQL Server的python脚本中包含变量

时间:2014-06-30 18:18:58

标签: python sql sql-server

我试图在调用MS SQL Server的python脚本中包含变量

import pyodbc

ip_addr = '10.10.10.10'

querystring = """SELECT USER_NAME
FROM sem6.sem_computer, [sem6].[V_SEM_COMPUTER], sem6.IDENTITY_MAP, sem6.SEM_CLIENT
WHERE [sem6].[V_SEM_COMPUTER].COMPUTER_ID = SEM_COMPUTER.COMPUTER_ID
AND sem6.SEM_CLIENT.GROUP_ID = IDENTITY_MAP.ID
AND sem6.SEM_CLIENT.COMPUTER_ID = SEM_COMPUTER.COMPUTER_ID
AND [IP_ADDR1_TEXT] = %s
"""

params = (ip_addr)

con = pyodbc.connect('DRIVER={SQL Server};SERVER=10.10.10.100;DATABASE=database;UID=username;PWD=password')
cur = con.cursor()
cur.execute(querystring, params)
result = cur.fetchone()[0]
print result
con.commit()
con.close()

它会出现以下错误

Traceback (most recent call last):
  File "database_test.py", line 17, in <module>
    cur.execute(querystring, params)
pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameter
s were supplied', 'HY000')

1 个答案:

答案 0 :(得分:1)

使用?而不是原始查询中的%s。