Re: fetchall() problem

84 views
Skip to first unread message
Message has been deleted

Alec Shaner

unread,
Jun 3, 2010, 10:34:00 AM6/3/10
to pyo...@googlegroups.com
I think your question is more about python in general than pyodbc, but you could so something like this:

print ', '.join(str(row.data) for row in cursor.execute("select data from column2").fetchall())

(Note, I did not test this...so hopefully it's correct).

Now you still have to manipulate the list to print exactly as you show below...but again that's just basic python stuff.

On Thu, Jun 3, 2010 at 7:40 AM, Jannis Syntychakis <ioa...@live.nl> wrote:
Hallo everybody,

somebody can help me with this:

code:

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=xxx;DATABASE=xxx1')
cursor = cnxn.cursor()
rows = cursor.execute("select data from column2").fetchall()
print rows


i get this:

[(38.0, ), (38.0, ), (38.0, ), (38.4375, ), (38.145000000000003, ),
(38.145000000000003, ), (38.700000000000003, )]

but i want to have only the numbers, something like this:

38.0 38.0 38.4375 38.145000000000003 38.145000000000003
38.700000000000003      or

38.0, 38.0, 38.4375, 38.145000000000003, 38.145000000000003,
38.700000000000003

somebody can help me?

thanks is advance,

Jannis

--
You received this message because you are subscribed to the Google Groups "pyodbc" group.
To post to this group, send email to pyo...@googlegroups.com.
To unsubscribe from this group, send email to pyodbc+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/pyodbc?hl=en.


Alec Shaner

unread,
Jun 3, 2010, 10:36:14 AM6/3/10
to pyo...@googlegroups.com
Sorry - ignore that last sentence in my previous email - initially I was just going to flatten the list of tuples to a list of values and forgot to edit.

mkleehammer

unread,
Jun 3, 2010, 10:46:37 AM6/3/10
to pyodbc
What you have is a list of Row objects: http://code.google.com/p/pyodbc/wiki/Rows

Rows are tuple-like objects, and in your case they contain a single
"column". The column value can be accessed in two ways: (1) like a
tuple by indexing, row[0] or (2) using the column name from the SQL
statement, row.data.

To extract them all, I'd recommend a quick list comprehension:

rows = cursor.execute(...).fetchall()
values = [ row.data for row in rows ]

Since cursors are iterable, you can also do something like:

values = [ row.data for row in cursor.execute(...) ]

The previous code created two lists: `rows` and `values`. This one
only creates a single list by iterating over cursor and adding to the
`values` list one row at a time.

Also, notice there is no fetchall(); it is iterating over the
execute() return value which is simply the cursor itself. That means
you can also break it into two lines if it is too unwieldy:

cursor.execute(...)
values = [ row.data for row in cursor ]

I hope this helps. Good luck!
Michael Kleehammer
Reply all
Reply to author
Forward
0 new messages