1

I have a table animal in a SQLSERVER database with two fields: id and name.

I'm trying to do this:

cnxn = pyodbc.connect(
    'Trusted_Connection=yes;DRIVER={SQL Server};SERVER=localhost; DATABASE=TEST;UID=sa;PWD=123456'
)

id = 1

cursor = cnxn.cursor()

cursor.execute('SELECT id, name FROM animal WHERE id=?', (id,))

for row in cursor.fetchall():
    print row.name

But for some reason it gives me the next error:

Traceback (most recent call last):

AttributeError: 'Row' object has no attribute 'name'

Can anyone help me to get the value from the field and save it in a variable?

1 Answer 1

1

Instead of print row.name use print row[1]. The fetchall() returns a list of tuples in the form [(1234, 'Alice Cooper'), ...]

Sign up to request clarification or add additional context in comments.

Comments

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.