Result Processing¶
Standard Usage (Unified Forms)¶
Since v2.6.0, SQL execution recommends only the following unified safe forms, all of which close/release connections automatically:
async with engine.execute(...) as result:— context manager, closes automatically on exit (including exception paths);async for row in engine.execute(...):— direct iteration, closes automatically when iteration completes or onbreak;fetch_all()/iterate()— close automatically after data is exhausted;- Statements without result sets (INSERT/UPDATE/DDL, etc.) — close the cursor and return the connection automatically after execution.
# Standard form 1: async with
async with engine.execute("SELECT * FROM users WHERE id = %s", (1,)) as result:
user = await result.fetch_one()
# Standard form 2: async for (also releases safely on break)
async for row in engine.execute("SELECT * FROM users", stream=True):
process(row)
❌ Not recommended: bare execution
r = engine.execute(...); await r()followed byfetch_one()/fetch_many()withoutclose(). Such usage can only rely on the GC safety net to discard the connection (see "Commit and Connection Release Semantics" below) and is not a standard form.
Retrieve Result Data¶
fetch_one() - Get Single Record¶
async with engine.execute("SELECT * FROM users WHERE id = %s", (1,)) as result:
user = await result.fetch_one()
if user:
print(user)
fetch_many() - Get Multiple Records¶
async with engine.execute("SELECT * FROM users") as result:
users = await result.fetch_many(10) # Get 10 records
for user in users:
print(user)
fetch_all() - Get All Records¶
async with engine.execute("SELECT * FROM users") as result:
all_users = await result.fetch_all()
print(f"Total {len(all_users)} records")
iterate() - Async Iterator¶
async with engine.execute("SELECT * FROM users") as result:
async for user in result.iterate():
print(user)
Direct Iteration of Result¶
# Method 1: Direct iteration of execute result
async for user in engine.execute("SELECT * FROM users"):
print(user)
# Method 2: Using async with then iterate
async with engine.execute("SELECT * FROM users") as result:
async for user in result:
print(user)
Result Types¶
Default tuple Type¶
async with engine.execute("SELECT id, name, email FROM users") as result:
user = await result.fetch_one()
# user is tuple: (1, "张三", "zhangsan@example.com")
dict Type¶
async with engine.execute("SELECT id, name, email FROM users", result_class=dict) as result:
user = await result.fetch_one()
# user is dict: {"id": 1, "name": "张三", "email": "zhangsan@example.com"}
Custom Model Type¶
from pydantic import BaseModel
from asmysql import Engine
class User(BaseModel):
id: int
name: str
email: str
engine = Engine(url="mysql://root:pass@127.0.0.1:3306/")
await engine.connect()
async with engine.execute("SELECT id, name, email FROM users", result_class=User) as result:
user = await result.fetch_one()
# user is User instance
print(user.name) # Use attribute access
Error Handling¶
Check Error¶
async with engine.execute("SELECT * FROM non_existent_table") as result:
if result.error:
print(f"Error code: {result.error_no}")
print(f"Error message: {result.error_msg}")
print(f"Error object: {result.error}")
else:
data = await result.fetch_all()
Error Attributes¶
result.error: Error exception object (MySQLErrororNone)result.error_no: Error code (integer, 0 when no error)result.error_msg: Error message (string, empty string when no error)
Since v2.4.0,
result.erroris stored with its__traceback__set toNone(severing the reference cycle between the exception's stack frames and theResultto avoid memory retention). Useerror_no/error_msgand the SQL inresult.queryfor troubleshooting; holdingresult.errorlong-term no longer keeps theResultobject alive; re-raising the exception produces a fresh traceback at the raise site.
Commit and Connection Release Semantics¶
- Successful statements:
COMMITis issued automatically when the server reports an open transaction (underautocommit=True, regular statements are auto-committed by the server and the client does not commit twice); - Failed statements:
ROLLBACKis issued automatically; partial writes are never committed; errors from the commit/rollback itself are also written toresult.error; - Statements without result sets (INSERT/UPDATE/DDL, etc.): the cursor is closed and the connection returned automatically after execution;
- Statements with result sets: the connection is returned when data is exhausted, on
close(), or onasync withexit; transactions of streaming statements with result sets are committed at that point; - Connections whose cursor close, commit/rollback, or
init_sqlfailed are discarded and never reused from the pool; - Task cancellation (
CancelledError): the connection is discarded synchronously and the slot returned; the cancellation signal propagates and does not enterresult.error; a cancelledResultis abandoned entirely — do not read its attributes or retry it. - Since v2.5.0, after
close()or the automatic release of statements without result sets, theresult.poolreference is cleared (typeOptional[Pool]): caching closedResultobjects no longer pins the connection pool and the event loop; - Since v2.6.0, GC safety net: an executed
Resultthat was not properly closed, when garbage-collected, synchronously discards its connection (closes the transport without sending COM_QUIT) and completes pool bookkeeping, emitting aResourceWarning; the connection is not returned to the pool for reuse, uncommitted transactions are rolled back by the server, and already auto-committed data is unaffected;disconnect()no longer hangs forever because of this. The safety net is only a fallback for misuse — production code must use the standard forms above; - Executing an unexecuted
Resultafterclose()raisesRuntimeError(Result is closed and cannot be executed again); re-enteringasync withon an already executedResultremains a no-op and never re-executes.
Execution Statistics¶
async with engine.execute("INSERT INTO users (name) VALUES (%s)", ("张三",)) as result:
# Affected rows
print(f"Affected rows: {result.row_count}")
# Last inserted ID (only for INSERT statements)
print(f"Last inserted ID: {result.last_rowid}")
Note:
- row_count returns None when using streaming query (stream=True)
- row_count returns None when an error occurs
- last_rowid is only valid for INSERT statements