使用PyODBC传递参数到存储过程
我正在使用pyODBC连接到一个SQL Server 2005 Express数据库。我在SQL Server Express中创建了一个存储过程,这个存储过程需要两个字符串参数,比如说stored_proc(input1, input2),这两个参数的类型是日期时间。我已经在管理工作室中测试过这个存储过程,它确实返回了正确的结果。然而,当我尝试从Python(我用的是Eclipse)调用这个存储过程时,出现了错误。
pyodbc.DataError: ('22018', '[22018] [Microsoft][SQL Native Client]无效的字符值用于转换规格 (0) (SQLExecDirectW)')2/9/2011 12:00:03 2/9/2011 12:20:03
我调用的函数如下:
def GetAlarmFrequencyTime(tstart,tend):
print tstart, tend
arguments=(tstart,tend)
local_cursor=conn.cursor()
local_cursor.execute("{call dbo.GetAlarmEventHistoryFrequency_TimeRange(tstart,tend)}")
resultset_rows=local_cursor.fetchall()
print "There are" , len(resultset_rows), "records"
for single_row in resultset_rows:
print "|" ,single_row[0], "|" ,single_row[1],"|"
local_cursor.close()
导致问题的那一行是
local_cursor.execute("{call dbo.GetAlarmEventHistoryFrequency_TimeRange(tstart,tend)}")
有没有人能帮我理解如何通过pyODBC向存储过程传递多个参数?我需要先把tstart和tend转换为日期时间格式吗?如果是的话,我该怎么做?我试过strptime,但即使这样也没有成功,可能是我用错了。
1 个回答
我终于搞定了,程序可以正常运行了,没有崩溃。
之前用的这行代码是错误的:local_cursor.execute("{call dbo.GetAlarmEventHistoryFrequency_TimeRange(tstart,tend)}"
正确的写法应该是:
local_cursor.execute("{call dbo.GetAlarmEventHistoryFrequency_TimeRange(?,?)}", (tstart), (tend))
特别要注意的是,里面的特殊符号 {} 和参数传递的方式,像这样 (tstart), (tend)。所以正确的代码是:local_cursor.execute("*{*call dbo.GetAlarmEventHistoryFrequency_TimeRange*(?,?)}", (tstart), (tend)*)