使用pyodbc将参数传递给sql查询失败

时间:2018-04-18 20:51:41

标签: sql parameters pyodbc

我已经阅读了几十篇类似的帖子并尝试了所有内容,但在尝试使用pyodbc将参数传递给简单查询时仍然收到错误消息。如果在其他地方有答案但我无法找到它,请道歉

我有一个非常简单的表格:

select * from Test

产量

a
b
c

这很好用:

import pyodbc
import pandas
connection = pyodbc.connect('DSN=HyperCube SYSTEST',autocommit=True)
result = pandas.read_sql("""select * from Test where value = 'a'""",connection,params=None)
print(result)

结果:

  value
0     a

但是,如果我尝试使用参数执行where子句则失败

result = pandas.read_sql("""select * from Test where value = ?""",connection,params='a')

产量

Error: ('01S02', '[01S02] Unknown column/parameter value (9001) (SQLPrepare)')

我也试过这个

cursor = connection.cursor()
cursor.execute("""select * from Test where value = ?""",['a'])
pyodbcResults = cursor.fetchall()

仍然收到同样的错误

有谁知道发生了什么事?这可能是我要查询的数据库的问题吗?

PS。我查看了以下帖子以及答案9第一部分中的语法,其中日期通过字符串传递,看起来与我正在做的相同

pyodbc sql包含0个参数标记,但提供了1个参数''hy000'

由于

1 个答案:

答案 0 :(得分:2)

  

pandas.read_sql(sql,con,index_col = None,coerce_float = True,params = None,parse_dates = None,columns = None,chunksize = None)[https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html]

     

params:list,tuple或dict,optional,default:None

示例:

cursor.execute("select * from Test where value = %s",['a'])

或命名参数示例:

result = pandas.read_sql(('select * from Test where value = %(par)s'),
               db,params={"par":'p'})

在pyodbc中直接在sql参数后写parms:

  

cursor.execute(sql,* parameters)

例如:

onepar = 'a'
cursor.execute("select * from Test where value = ?", onepar)

cursor.execute("select a from tbl where b=? and c=?", x, y)
相关问题