我在插入datetamp参数时遇到问题。在这里,您可以看到从文字版本(1)到字符串格式版本(2)到错误状态版本的升级。 (注意DateFrom
和DateTo
):
sql = "sp_report ProfitAndLossStandard show Amount_Title, Text, Label, Amount parameters DateFrom = {d'2018-02-12'}, DateTo = {d'2018-02-18'}, SummarizeColumnsBy='TotalOnly', ReturnRows='All'"
sql = "sp_report ProfitAndLossStandard show Amount_Title, Text, Label, Amount parameters DateFrom = %s, DateTo = %s, SummarizeColumnsBy='TotalOnly', ReturnRows='All'" % (q_startdate, q_enddate)
随后尝试使用插入语法?
,cursor.execute(sql, (q_startdate), (q_enddate))
和变量:
q_startdate = ("{d'%s'}" % dates[0])
q_enddate = ("{d'%s'}" % dates[1])
sql = "sp_report ProfitAndLossStandard show Amount_Title, Text, Label, Amount parameters DateFrom = ?, DateTo = ?, SummarizeColumnsBy='TotalOnly', ReturnRows='All'"
>>> ('HY004', '[HY004] [Microsoft][ODBC Driver Manager] SQL data type out of range (0) (SQLBindParameter)')
q_startdate = (dates[0])
q_enddate = (dates[1])
sql = "sp_report ProfitAndLossStandard show Amount_Title, Text, Label, Amount parameters DateFrom = {d'?'}, DateTo = {d'?'}, SummarizeColumnsBy='TotalOnly', ReturnRows='All'"
>>> ('42000', "[42000] [QODBC] [sql syntax error] Expected lexical element not found: = {d'?'} (11015) (SQLPrepare)")
阅读pyodbc
Wiki page on inserting data时,我没有看到插入字符串有任何减速带。这一定与pyodbc如何处理(转义)日期戳有关。
如何参数化日期戳-特别是使用qodbc
flavor of datestamp。
答案 0 :(得分:1)
几乎不需要在pyodbc参数化查询中使用{d'2018-02-12'}
之类的ODBC转义序列。如果参数值是真正的Python date对象
q_startdate = date(2018, 2, 12)
然后pyodbc将通知ODBC驱动程序该参数值为SQL_TYPE_DATE
,如ODBC跟踪日志中所示
[ODBC][2984][1532535987.825823][SQLBindParameter.c][217]
Entry:
Statement = 0x1f1a6b0
Param Number = 1
Param Type = 1
C Type = 91 SQL_C_TYPE_DATE
SQL Type = 91 SQL_TYPE_DATE
Col Def = 10
Scale = 0
Rgb Value = 0x1f3ac78
Value Max = 0
StrLen Or Ind = 0x1f3ac58
,我们只能在SQL命令文本中使用裸参数占位符
... parameters DateFrom = ?, ...