[Python][aiomysql] DictCursor
DictCursor
How did I encounter this?
While implementing a feature that updates the pre-existing row in game_db, it was required to verify which columns of the row are to be updated. However, the usual way of sending the query of SELECT doesn't provide column names to check. I found a way: DictCursor from aiomysql.
Syntax
By default, rows fetched from a query are returned as tuples. WithDictCursor, rows are returned as dictionaries, making it easier to access values using column names instead of relying on indices.Example
async with conn.cursor() as cur:
await cur.execute("SELECT id, title FROM game_table LIMIT 5;")
rows = await cur.fetchall()
# rows is a list of dict, e.g. [{"id": 1, "title": "God of War"}, ...]
for row in rows:
print(row["id"], row["title"])
conn.close()
Comments
Post a Comment