pyodbc the sql contains 0 parameter markers but 1 parameters were supplied' 'hy000'

元气小坏坏 提交于 2019-11-29 02:26:50
themiurge

Parameters in an SQL statement via ODBC are positional, and marked by a ?. Thus:

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

Plus, it's better to avoid passing dates as strings. Let pyodbc take care of that using Python's datetime:

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)

then just pass the parameters as above. If you prefer string parsing, see this answer.

i tryied and have a lot of different errors: 42000, 22007, 07002 and others

The work version is bellow:

import sys
import pyodbc
import datetime

# connection parameters
nHost = 'host'
nBase = 'DBname'
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)
    except:
        print ("connection failed check authorization parameters")  
con = sqlconnect(nHost,nBase,nUser,nPasw)
cursor = con.cursor()
# make connection stop

STARTDATE = '11/2/2017'
ENDDATE = '12/2/2017'
params = (STARTDATE, ENDDATE)

# SQL with parameters start
sql = ('''
SELECT * FROM TABLE 
WHERE TABLE.TIMESTAMP BETWEEN CAST(? as datetime) AND CAST(? as datetime)
''')
# SQL with parameters stop

# print result to console start
query = cursor.execute(sql, params)
row = query.fetchone()
while row:
    print (row)
    row = query.fetchone()
# print result to console stop  
say = input ('everething is ok, you can close console')

I had a similar issue. Saw that downgrading the version of PyODBC to 4.0.6 and SQLAlchemy to 1.2.9 fixed the error,using Python 3.6

Kevin Ruder

If you're trying to use pd.to_sql() like me I fixed the problem by passing a parameter called chunksize.

df.to_sql("tableName", engine ,if_exists='append', chunksize=50)

hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!