2

I need to retrieve values from the database for the column names specified. The below code I've tried,

import pyodbc

def get_db_data():
    cursor = getConnection.cursor()
    cursor.execute("select * from student")
    return cursor

cur = get_db_data()
for row in cur.fetchall():
    print(row["student_name"])

I'm facing below error

TypeError: row indices must be integers, not str

How to achieve this?

2 Answers 2

1

If you want to access a column by name, you should specify it as an attribute of the row rather than an index:

for row in cur.fetchall():
    print(row.student_name)
Sign up to request clarification or add additional context in comments.

Comments

0

As per the pyodbc documentation "Row objects are similar to tuples, but they also allow access to columns by name". You can try row[0] or row.student_name (Assuming column index for student_name is 0)

import pyodbc

def get_db_data():
    cursor = getConnection.cursor()
    cursor.execute("select * from student")
    return cursor

cur = get_db_data()
for row in cur.fetchall():
    print(row[0]) 

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.