0

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 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Looks like they updated their docs too. It's the first example on this page... pymssql.org/en/latest/pymssql_examples.html In my use case there should always be data returning from the table in question. If the table has no rows then raising an exception would be the desired behavior.

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.