使用pythonpyodb捕获存储过程输出

2024-10-01 13:24:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用Python脚本和Pyodbc模块调用的存储过程。代码如下:

import pyodbc
pyodbc.pooling=False
oConnexion = pyodbc.connect("driver={Teradata};dbcname=myServer;DefaultDatabase=myDB;uid=myUser;pwd=myPassword;charset=utf8;", autocommit=True)
oConnexion.setdecoding(pyodbc.SQL_CHAR, encoding='utf-8')
oConnexion.setdecoding(pyodbc.SQL_WCHAR, encoding='utf-8')
oConnexion.setencoding(encoding='utf-8')
oCursor = oConnexion.cursor()
oQueryRegisterBatch = "CALL DEV_AUDIT.SP_AUDIT_BATCH('ED_DATA_QUALITY_MANUAL', 'REGISTER', '1900-01-01 00:00:00.000000', '2999-12-31 00:00:00.000000');"
oCursor.execute(oQueryRegisterBatch)
for row in oCursor:
    print (row)

存储过程将创建一个新记录并返回记录id(批处理密钥)。当我在Teradata中执行存储过程时,它会正确地返回BATCH_键,但我无法用Python捕获它。我收到以下错误消息而不是值:

^{pr2}$

我可以在调用存储过程后通过查询表来检索BATCH_键,但我希望避免。您能告诉我如何捕获存储过程的输出吗?在

谢谢


Tags: 脚本sql过程batch记录auditutfencoding
1条回答
网友
1楼 · 发布于 2024-10-01 13:24:55

根据pyodbc包的文档,不可能捕获存储过程的输出。这里有记录:https://github.com/mkleehammer/pyodbc/wiki/Calling-Stored-Procedures

pyodbc does not currently implement the optional .callproc method.

有一种方法可以根据您的数据库引擎工作,即将对存储过程的调用嵌入到查询中。在

Because pyodbc does not have .callproc we need to use a workaround for retrieving the values of output parameters and return values. The specific method will depend on what your particular ODBC driver supports, but for Microsoft's ODBC drivers for SQL Server we can use an "anonymous code block" to EXEC the stored procedure and then SELECT the output parameters and/or return values.

详见以上链接。在

相关问题 更多 >