gpt4 book ai didi

python - 标准输出 pymssql 到变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:10:27 28 4
gpt4 key购买 nike

我正在尝试检索运行的结果表单

import pymssql
conn = pymssql.connect(server='IP', user='domain\user', password='PSWD', tds_version='8.0')
cursor = conn.cursor()
cursor.execute("EXEC msdb.dbo.sp_start_job @job_name = 'jobname'")

当它将作业添加到提示中进行处理时,它不会返回任何内容,但是当作业未运行时,它会像测试用例一样返回内容

Traceback (most recent call last):
File "shared/python3", line 85, in <module>
cursor.execute("EXEC msdb.dbo.sp_start_job @job_name = ''")
File "pymssql.pyx", line 467, in pymssql.Cursor.execute (pymssql.c:7533)
pymssql.OperationalError: (14262, "The specified @job_name ('') does not exist.DB-Lib error message 14262, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n")

在这种情况下,错误指出 Job_name 不存在。我想要做的是将结果放在一个字符串变量上,我可以对其进行解析以进行错误控制...

我试过这个:

import sys

# Store the reference, in case you want to show things again in standard output
old_stdout = sys.stdout

# This variable will store everything that is sent to the standard output
result = StringIO()
sys.stdout = result

# Here we can call anything we like, like external modules, and everything that they will send to standard output will be stored on "result"
cursor.execute("EXEC msdb.dbo.sp_start_job @job_name = 'jobname'")

# Redirect again the std output to screen
sys.stdout = old_stdout

# Then, get the stdout like a string and process it!
result_string = result.getvalue()
process_string(result_string)

link .但无法让它工作。

最佳答案

您看到回溯是因为您没有处理作业名称不存在时发生的异常。如果你想捕获错误消息,你可以简单地捕获异常。作为一个通用的例子,而不是仅仅做

crsr.execute(sql)

你可以做

try:
crsr.execute(sql)
except Exception as e:
(error_code, error_message) = e

然后使用 error_codeerror_message 值将它们写入日志文件,或将它们输出到控制台,或其他任何方式。

关于python - 标准输出 pymssql 到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37809872/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com