How to get the sql print message using pymssql

拟墨画扇 提交于 2021-02-08 05:02:24

问题


I'm running some queries, that print runtime stats from their execution.

It's done through print('message') used within the sql script.

I would want to see these messages while calling the procedures/scripts through pymssql.

conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor()
cursor.execute("print('message')")
conn.commit()

Above script doesn't return anything, and I can't find any tips on how to get that print to show up in the console output.


回答1:


Found a solution that let's me still use pymssql and get the print messages. pymssql.Connection actually uses _mssql.MSSQLConnection internally. This means that you can use this example by accessing that internal object.

connection = pymssql.connect(server='server_address', database='db_name')
connection._conn.set_msghandler(my_msg_handler)  # Install our custom handler

where the my_msg_handler is the same type of object as in pmssql wiki. Accessing internal objects is not ideal, but it's the only way I've found if you don't want to use a different library and need to get the SQL prints.




回答2:


In order to print something into the console in pymssql, you don't need to put the print inside the execute function. you can simply use

print("message")

so your code will be

conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor()
print("message")
conn.commit()



回答3:


I don't believe there is a way, but you can refactor your SQL. For example:

DECLARE @my_var AS VARCHAR(200)
PRINT 'Setting a variable...'
SET @my_var = 'this'
PRINT 'I am some output'
SELECT * FROM my_table WHERE this = @my_var

Could be refactored to be something like this:

DECLARE @my_var AS VARCHAR(200)
DECLARE @messages AS VARCHAR(MAX)
SET @messages = @messages + 'Setting a variable...'
SET @my_var = 'this'
SET @messages = @messages + 'I am some output'
SELECT @messages, * FROM my_table WHERE this = @my_var

Good luck!



来源:https://stackoverflow.com/questions/47396196/how-to-get-the-sql-print-message-using-pymssql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!