Search code examples
pythonsqlpymssql

pymssql: access data in cursor without for loop


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?


Solution

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