使用PyODBC将参数传递给存储过程

时间:2011-10-19 15:51:20

标签: python sql-server-2005 pyodbc

我正在使用pyODBC连接到SQL Server 2005 Express数据库。我在SQLServer express中创建了一个存储过程,它接受2个字符串参数,例如stored_proc(inpu1,input2),这些参数的类型为datetime。我已经使用管理工作室测试了存储过程,它确实返回了适当的结果。但是当我尝试从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,并首先采用日期时间格式,如果是这样的话?我已经完成了strptime,但即使这样也没有成功,尽管我可能使用了错误

1 个答案:

答案 0 :(得分:4)

我终于明白了,工作没有崩溃

  

local_cursor.execute(“{call dbo.GetAlarmEventHistoryFrequency_TimeRange(tstart,tend)}”)

是错误的语法。它应该是

  

local_cursor.execute(“{call dbo.GetAlarmEventHistoryFrequency_TimeRange(?,?)}”,(tstart),(tend))

应特别注意特殊符号{}和传递参数的方式(tstart),(倾向)local_cursor.execute(“ * { * call dbo.GetAlarmEventHistoryFrequency_TimeRange * <强>(?,?)的 }”,<强> (TSTART),(倾向于)*