如何传递日期参数以在python pandas中执行sql存储过程

时间:2019-10-23 21:49:04

标签: python python-3.x pandas

这种方式有效:

import pandas
import pyodbc
import datetime as dt  

server = 'myserver'
db = 'mydb' 
myparams = ['2017-02-01','2017-02-28', None]  # None substitutes NULL in sql

connection_string = pyodbc.connect('DRIVER={SQL Server};server='+server+';DATABASE='+ db+';Trusted_Connection=yes;')
df = pandas.read_sql_query('EXEC PythonTest_Align_RSrptAccountCurrentMunich @EffectiveDateFrom=?,@EffectiveDateTo=?,@ProducerLocationID=?', connection_string, params = myparams)

但是这种方法不起作用:

import datetime as dt

today = dt.date.today()
prev_monday = today - dt.timedelta(days=9)
prev_sunday = today - dt.timedelta(days=3)

myparams = [prev_monday,prev_sunday, None]  # None substitutes NULL in sql

connection_string = pyodbc.connect('DRIVER={SQL Server};server='+server+';DATABASE='+ db+';Trusted_Connection=yes;')
df = pandas.read_sql_query('EXEC PythonTest_Align_RSrptAccountCurrentMunich @EffectiveDateFrom=?,@EffectiveDateTo=?,@ProducerLocationID=?', connection_string, params = myparams)

错误消息:

    cur.execute(*args)
pandas.io.sql.DatabaseError: Execution failed on sql 'EXEC PythonTest_Align_RSrptAccountCurrentMunich @EffectiveDateFrom=?,@EffectiveDateTo=?,@ProducerLocationID=?': ('HYC00', '[HYC00] [Microsoft][ODBC SQL Server Driver]Optional feature not implemented (0) (SQLBindParameter)')

在python中有传递日期参数的特定方法吗?

1 个答案:

答案 0 :(得分:1)

我的猜测是SQL无法处理熊猫的datetime值,

尝试使用strftime

将日期时间值传递给strigns
import datetime as dt

today = dt.date.today()
prev_monday = (today - dt.timedelta(days=9)).strftime('%Y-%m-%d')
prev_sunday = (today - dt.timedelta(days=3)).strftime('%Y-%m-%d')

myparams = [prev_monday,prev_sunday, None]
print(myparams)
['2019-10-14', '2019-10-20', None]