7

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?

Justin Dearing
  • 14,270
  • 22
  • 88
  • 161
ijk
  • 175
  • 1
  • 7
  • At the TDS level. PRINT and RAISERROR() both send query output "in band" with the resultsets. However, the data is not a TDS resultset, and it does appear the driver does not handle it properly. – Justin Dearing Jan 13 '15 at 22:24

2 Answers2

1

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!

Chef Slagle
  • 389
  • 3
  • 7
0

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.

Mr Moose
  • 5,946
  • 7
  • 34
  • 69