3

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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!

1 Comment

Thanks for the answer, good idea. Sadly, this is to support a CI solution for a database with over 6000 scripts, so .... I'm not convincing anyone to refactor all that :) While trying to make this work I had learned that _mssql, which is part of the pymssql package, is actually able to return the messages, but in this case I have issues with integrated login use. I'll post some info if I find a solution.
-1

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()

2 Comments

Let me rephrase, I have an existing process in SQL that has prints, and I need to see those in console output.
@Shammas The question is about seeing the output of print statements that are inside SQL stored procedures, for example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.