pymssql: access data in cursor without for loop

1.7k views Asked by At

I am retrieving a single row from a single column in my database. The pymssql documentation exclusively uses loops to access the data in a cursor.

conn = pymssql.connect(server, user, password, "tempdb")
cursor = conn.cursor()
cursor.execute('SELECT %s', 'Foo')

#This works but it's ugly
for row in cursor:
    print row[0]
    break

#The following throws an error
print cursor[0][0]

conn.close()

Is there a way to access the data inside the cursor object without a for loop?

1

There are 1 answers

1
circuitBurn On BEST ANSWER

You can use cursor.fetchone()[0] in place of cursor[0][0].

However, if nothing is returned from the query you're going to get an exception. Better to do something "ugly" like this:

row = cursor.fetchone()
if row:
    print row[0]