I'm using Flask SQLAlchemy and I have the following code to get users from the database via a raw SQL query from the MySQL database:
connection = engine.raw_connection() cursor = connection.cursor() cursor.execute("SELECT * from User where id=0") results = cursor.fetchall()
results
The variable is a tuple and I want it to be of type dict(). Is there any way to achieve this?
When I use pymysql to build the database connection, I am able to do
cursor = connection.cursor(pymysql.cursors.DictCursor)
Is there something similar in SQLAlchemy?
NOTE: The reason I want to make this change is to get rid of using pymysql in my code and just use the SQLAlcehmy functionality, i.e. I don't want to have "import pymysql" anywhere in my code.
You can use sqlalchemy cursors and cursor descriptions.
Updated answer for SQLAlchemy 1.4:
Version 1.4 has deprecated the old
engine.execute()
mode and changed the way.execute()
operates internally..execute()
now returns a CursorResult object with the .mappings () method:(Previous answer for SQLAlchemy 1.3)
If you use
engine.execute
instead ofraw_connection()
, SQLAlchemy already does this for you. Usingengine.execute
,fetchone
will return a SQLAlchemyRow
object,fetchall
will return alist
Row
Object.Row
objects can be accessed by key, just likedict
:If you need a real
dict
object, then you can just convert it: