ijk
ijk

Reputation: 175

sql print statements from pyodbc

How do I get the output from the sql_query?

import pyodbc

sql_query = "print 'Hello World'"

conn = pyodbc.connect("DRIVER={SQL Server};
SERVER=myserver;
DATABASE=mydatabase;
UID=myusername;
PWD=mypassword")

cur = conn.cursor()

cur.execute(sql_query)
cur.commit()

for row in cursor.fetchall():
    print row

So far I think an SQL print is out of band from the usual structured responses?

http://www.easysoft.com/developer/languages/perl/sql_server_unix_tutorial.html#print_statement_status_messages has something similar to what I'm trying to do in Perl.

The closest I can see is the optional: http://www.python.org/dev/peps/pep-0249/#cursor-messages So I guess it's just not implemented?

Upvotes: 7

Views: 4996

Answers (2)

Chef Slagle
Chef Slagle

Reputation: 387

When running the query PRINT 'Hello World' the output is being returned as console output (string), and fetchall is reviewing the result set (object) from a query. RAISERROR is an error condition, and can stop the process. I'm not saying this isn't a solution, but maybe you just want to print some feedback without creating an error condition.

I think you can achieve the result you are looking for by changing

[PRINT 'Hello World'] to [SELECT 'Hello World']

I think this will create a single row of data in a result set with the text you wanted in it, that should show up in fetchall, and see if you get the results you are expecting.

Hope that helps provide an alternative you can try!

Upvotes: 1

Mr Moose
Mr Moose

Reputation: 6354

Use RAISERROR over PRINT. Use it with NOWAIT to get output immediately. I don't know how to handle this in python, but in ADO.NET you can use the InfoMessage event on SqlConnection. Maybe there is something similar in Python.

Upvotes: 0

Related Questions