8

I am having an issue when I select data from the SQL database through pyodbc where I end up with this type of result.

[(55.0, )]

I want the pure number (no "[" or "(" so I later can insert it into a different table after calculating new stuff with it. I am sure it's trivial but I just haven't been able to figure out how. Below is the code I am using:

rows = conn.execute("SELECT price from PG").fetchall()
print(rows[:1])
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
MathiasRa
  • 825
  • 2
  • 12
  • 24

2 Answers2

16

Note for future readers: The pyodbc Cursor object has a fetchval method:

The fetchval() convenience method returns the first column of the first row if there are results, otherwise it returns None.

(It is similar to the .NET ExecuteScalar() method.)

So instead of doing something like

row_count = crsr.execute("SELECT COUNT(*) FROM TableName").fetchone()[0]

we can just do

row_count = crsr.execute("SELECT COUNT(*) FROM TableName").fetchval()

It has the added advantage of returning None (instead of throwing an exception) if the query returns no rows.

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
  • Sadly, `fetchval` is pyodbc-specific and [pypyodbc doesn't have it](https://github.com/jiangwen365/pypyodbc/search?q=fetchval&unscoped_q=fetchval). – Nickolay Sep 03 '18 at 13:28
  • 2
    @Nickolay I believe the OP only asked for pyodbc. – NoName Feb 05 '20 at 02:35
2

You have [(55.0, )] because you have a list of rows (containing a single row in this example), and each row is a tuple (with a single element, since you just selected price). You can do

singlerow = rows[0]
price, = singlerow

However, fetching all rows to select just one seems weird, you should probably re-think your query.

blue_note
  • 27,712
  • 9
  • 72
  • 90