Reputation: 608
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?
Upvotes: 2
Views: 560
Reputation: 643
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])
Upvotes: 0
Reputation: 106936
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)
Upvotes: 1