gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:06:22 26 4
gpt4 key购买 nike

我正在使用 Python 3.6、pyodbc,并连接到 SQL Server。

我正在尝试连接到数据库,然后创建带参数的查询。

代码如下:

import sys
import pyodbc

# connection parameters
nHost = 'host'
nBase = 'base'
nUser = 'user'
nPasw = 'pass'

# make connection start
def sqlconnect(nHost,nBase,nUser,nPasw):
try:
return pyodbc.connect('DRIVER={SQL Server};SERVER='+nHost+';DATABASE='+nBase+';UID='+nUser+';PWD='+nPasw)
print("connection successfull")
except:
print ("connection failed check authorization parameters")
con = sqlconnect(nHost,nBase,nUser,nPasw)
cursor = con.cursor()
# make connection stop

# if run WITHOUT parameters THEN everything is OK
ask = input ('Go WITHOUT parameters y/n ?')
if ask == 'y':
# SQL without parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN '2017-03-01T00:00:00.000' AND '2017-03-01T01:00:00.000'
''')
# SQL without parameters stop

# print result to console start
row = res.fetchone()
while row:
print (row)
row = res.fetchone()
# print result to console stop

# if run WITH parameters THEN ERROR
ask = input ('Go WITH parameters y/n ?')
if ask == 'y':

# parameters start
STARTDATE = "'2017-03-01T00:00:00.000'"
ENDDATE = "'2017-03-01T01:00:00.000'"
# parameters end

# SQL with parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN :STARTDATE AND :ENDDATE
''', {"STARTDATE": STARTDATE, "ENDDATE": ENDDATE})
# SQL with parameters stop

# print result to console start
row = res.fetchone()
while row:
print (row)
row = res.fetchone()
# print result to console stop

当我在 SQL 中运行不带参数的程序时,它工作正常。

当我尝试使用参数运行它时,发生错误。

最佳答案

通过 ODBC 的 SQL 语句中的参数是位置性的,并由 ? 标记。因此:

# SQL with parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN ? AND ?
''', STARTDATE, ENDDATE)
# SQL with parameters stop

此外,最好避免将日期作为字符串传递。让 pyodbc 使用 Python 的日期时间来处理这个问题:

from datetime import datetime
...
STARTDATE = datetime(year=2017, month=3, day=1)
ENDDATE = datetime(year=2017, month=3, day=1, hour=0, minute=0, second=1)

然后像上面那样传递参数。如果您更喜欢字符串解析,请参阅 this answer .

关于python - pyodbc sql 包含 0 个参数标记,但提供了 1 个参数' 'hy000',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43491381/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com