Error getting data in Python

0

I have this code in a Python 3.7.0 program that theoretically should not give an error:

    import pyodbc
import csv

conn = pyodbc.connect('DSN=EDISOFT')
cursor = conn.cursor()

for row in cursor.execute ("select top 100 isbn,ean, titulo, pvp from art"):
    print (row.isbn, row.ean, row.titulo, row.pvp )
cursor.close()
conn.close()

However, he throws me:

AttributeError: 'pyodbc.Row' object has no attribute 'isbn'

If instead of the name of the column I put the ordinal of the row [0] field, it does not give me an error.

Any suggestions?

Thanks in advance.

    
asked by ertato 20.09.2018 в 08:39
source

1 answer

0

I think you should use cursor.fetchall () according to the pyodbc documentation

The code would remain this way

import pyodbc
import csv

conn = pyodbc.connect('DSN=EDISOFT')
cursor = conn.cursor()
cursor.execute("select top 100 isbn,ean, titulo, pvp from art")
rows = cursor.fetchall()
for row in rows:
    print (row.isbn, row.ean, row.titulo, row.pvp )
cursor.close()
conn.close()

EDIT:

It seems that in rows you are not returning row objects, as the documentation requires.

I propose the following solution, create a function that transforms the result of the cursor into a list of dictionaries to facilitate reference to field names. The code could look like this:

import pyodbc

def dictfetchall(cursor):
    desc = cursor.description
    return [
            dict(zip([col[0] for col in desc], row))
            for row in cursor.fetchall()
           ]

conn = pyodbc.connect('DSN=EDISOFT')
cursor = conn.cursor()
cursor.execute("select top 100 isbn,ean, titulo, pvp from art")
rows = cursor.dictfetchall()
for row in rows:
    print (row.get('isbn'), row.get('ean'), row.get('titulo'), row.get('pvp'))
cursor.close()
conn.close()

Another solution without having to use the function to pass the result to a list of dictionaries may be to change the sql statement to the following

cursor.execute('select top 100 "isbn" as isbn, "ean" as ean, "titulo" as titulo, "pvp" as pvp from art')

It seems that in some connections it requires a format like this.

    
answered by 20.09.2018 в 12:13