Skip to content

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 on break;
  • 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 by fetch_one() / fetch_many() without close(). 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 (MySQLError or None)
  • 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.error is stored with its __traceback__ set to None (severing the reference cycle between the exception's stack frames and the Result to avoid memory retention). Use error_no / error_msg and the SQL in result.query for troubleshooting; holding result.error long-term no longer keeps the Result object alive; re-raising the exception produces a fresh traceback at the raise site.

Commit and Connection Release Semantics

  • Successful statements: COMMIT is issued automatically when the server reports an open transaction (under autocommit=True, regular statements are auto-committed by the server and the client does not commit twice);
  • Failed statements: ROLLBACK is issued automatically; partial writes are never committed; errors from the commit/rollback itself are also written to result.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 on async with exit; transactions of streaming statements with result sets are committed at that point;
  • Connections whose cursor close, commit/rollback, or init_sql failed 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 enter result.error; a cancelled Result is 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, the result.pool reference is cleared (type Optional[Pool]): caching closed Result objects no longer pins the connection pool and the event loop;
  • Since v2.6.0, GC safety net: an executed Result that was not properly closed, when garbage-collected, synchronously discards its connection (closes the transport without sending COM_QUIT) and completes pool bookkeeping, emitting a ResourceWarning; 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 Result after close() raises RuntimeError (Result is closed and cannot be executed again); re-entering async with on an already executed Result remains 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