Search code examples
python-3.4pymssqlconsole-output

How to get the sql print message using pymssql


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.


Solution

  • 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.