Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have pyodbc return a simple (scalar) value for a query that only returns one item

Tags:

python

pyodbc

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])
like image 702
MathiasRa Avatar asked Oct 16 '17 17:10

MathiasRa


People also ask

What does pyodbc connect return?

What does Pyodbc connect return? Returns a new Cursor Object using the connection. pyodbc supports multiple cursors per connection but your database may not.

What is the difference between pyodbc and Sqlalchemy?

PyODBC allows you connecting to and using an ODBC database using the standard DB API 2.0. SQL Alchemy is a toolkit that resides one level higher than that and provides a variety of features: Object-relational mapping (ORM) Query constructions.

What does pyodbc do in Python?

Pyodbc is an open source Python module that makes accessing ODBC databases simple. It implements the DB API 2.0 specification. Using pyodbc, you can easily connect Python applications to data sources with an ODBC driver.

What is cursor in pyodbc?

wiki. Cursors represent a database cursor (and map to ODBC HSTMTs), which is used to manage the context of a fetch operation. Cursors created from the same connection are not isolated, i.e., any changes done to the database by a cursor are immediately visible by the other cursors.


2 Answers

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.

like image 135
Gord Thompson Avatar answered Oct 18 '22 21:10

Gord Thompson


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.

like image 35
blue_note Avatar answered Oct 18 '22 19:10

blue_note