MySQL driver for asyncio providing async/await support for database operations.
npx @tessl/cli install tessl/pypi-aiomysql@0.2.00
# aiomysql
1
2
A pure-Python MySQL client library providing async/await support for asyncio applications. Built on top of PyMySQL, aiomysql enables non-blocking database operations while maintaining compatibility with the MySQL protocol and offering connection pooling capabilities.
3
4
## Package Information
5
6
- **Package Name**: aiomysql
7
- **Language**: Python
8
- **Installation**: `pip install aiomysql`
9
- **Dependencies**: PyMySQL>=1.0, optional SQLAlchemy support
10
11
## Core Imports
12
13
```python
14
import aiomysql
15
```
16
17
Individual components:
18
19
```python
20
from aiomysql import connect, create_pool, Connection, Pool
21
from aiomysql import Cursor, DictCursor, SSCursor, SSDictCursor
22
```
23
24
## Basic Usage
25
26
```python
27
import asyncio
28
import aiomysql
29
30
async def main():
31
# Connect to MySQL database
32
conn = await aiomysql.connect(
33
host='localhost',
34
port=3306,
35
user='root',
36
password='password',
37
db='test'
38
)
39
40
# Create cursor and execute query
41
async with conn.cursor() as cur:
42
await cur.execute("SELECT 42")
43
result = await cur.fetchone()
44
print(result) # (42,)
45
46
# Close connection
47
conn.close()
48
49
# Run the example
50
asyncio.run(main())
51
```
52
53
## Architecture
54
55
aiomysql provides two main integration approaches:
56
57
- **Direct MySQL Integration**: Low-level async MySQL connectivity with cursors, connections, and pools
58
- **SQLAlchemy Integration**: High-level ORM-style operations through the `aiomysql.sa` subpackage
59
60
The library maintains full compatibility with MySQL and MariaDB servers while providing async/await support for all database operations including transactions, connection pooling, and different cursor types for various data access patterns.
61
62
## Capabilities
63
64
### Database Connections
65
66
Create and manage individual MySQL database connections with support for SSL, authentication plugins, and connection configuration.
67
68
```python { .api }
69
def connect(
70
host: str = "localhost",
71
user: str = None,
72
password: str = "",
73
db: str = None,
74
port: int = 3306,
75
unix_socket: str = None,
76
charset: str = '',
77
sql_mode: str = None,
78
read_default_file: str = None,
79
conv: dict = None,
80
use_unicode: bool = None,
81
client_flag: int = 0,
82
cursorclass: type = Cursor,
83
init_command: str = None,
84
connect_timeout: int = None,
85
read_default_group: str = None,
86
autocommit: bool = False,
87
echo: bool = False,
88
local_infile: bool = False,
89
loop = None,
90
ssl: dict = None,
91
auth_plugin: str = '',
92
program_name: str = '',
93
server_public_key: str = None
94
) -> _ConnectionContextManager: ...
95
```
96
97
[Database Connections](./connections.md)
98
99
### Connection Pooling
100
101
Manage multiple database connections efficiently with connection pooling, supporting minimum and maximum pool sizes, connection recycling, and pool lifecycle management.
102
103
```python { .api }
104
def create_pool(
105
minsize: int = 1,
106
maxsize: int = 10,
107
echo: bool = False,
108
pool_recycle: int = -1,
109
loop = None,
110
**kwargs
111
) -> _PoolContextManager: ...
112
```
113
114
[Connection Pooling](./pooling.md)
115
116
### Cursors and Data Access
117
118
Execute SQL queries and retrieve results using different cursor types optimized for various use cases, from simple queries to large result sets and dictionary-style data access.
119
120
```python { .api }
121
class Cursor:
122
async def execute(self, query: str, args = None) -> int: ...
123
async def executemany(self, query: str, args) -> int: ...
124
def fetchone(self) -> tuple: ...
125
def fetchmany(self, size: int = None) -> list: ...
126
def fetchall(self) -> list: ...
127
128
class DictCursor(Cursor):
129
def fetchone(self) -> dict: ...
130
def fetchmany(self, size: int = None) -> list: ...
131
def fetchall(self) -> list: ...
132
133
class SSCursor(Cursor):
134
async def fetchone(self) -> tuple: ...
135
async def fetchmany(self, size: int = None) -> list: ...
136
async def fetchall(self) -> list: ...
137
138
class SSDictCursor(SSCursor):
139
async def fetchone(self) -> dict: ...
140
async def fetchmany(self, size: int = None) -> list: ...
141
async def fetchall(self) -> list: ...
142
```
143
144
[Cursors and Data Access](./cursors.md)
145
146
### SQLAlchemy Integration
147
148
High-level database operations using SQLAlchemy's expression language and ORM capabilities with async/await support through the `aiomysql.sa` subpackage.
149
150
```python { .api }
151
async def create_engine(
152
minsize: int = 1,
153
maxsize: int = 10,
154
loop = None,
155
dialect = None,
156
pool_recycle: int = -1,
157
compiled_cache = None,
158
**kwargs
159
) -> Engine: ...
160
```
161
162
[SQLAlchemy Integration](./sqlalchemy.md)
163
164
## Exception Types
165
166
```python { .api }
167
# Base exceptions
168
class Error(Exception): ...
169
class Warning(Exception): ...
170
171
# Interface and database errors
172
class InterfaceError(Error): ...
173
class DatabaseError(Error): ...
174
class DataError(DatabaseError): ...
175
class OperationalError(DatabaseError): ...
176
class IntegrityError(DatabaseError): ...
177
class InternalError(DatabaseError): ...
178
class ProgrammingError(DatabaseError): ...
179
class NotSupportedError(DatabaseError): ...
180
181
# MySQL-specific error
182
class MySQLError(Exception): ...
183
```
184
185
## Context Manager Types
186
187
```python { .api }
188
class _ConnectionContextManager:
189
"""Context manager for database connections."""
190
async def __aenter__(self) -> Connection: ...
191
async def __aexit__(self, exc_type, exc_val, exc_tb): ...
192
193
class _PoolContextManager:
194
"""Context manager for connection pools."""
195
async def __aenter__(self) -> Pool: ...
196
async def __aexit__(self, exc_type, exc_val, exc_tb): ...
197
```
198
199
## Utility Functions
200
201
```python { .api }
202
def escape_string(s: str) -> str: ...
203
def escape_dict(d: dict, charset: str) -> dict: ...
204
def escape_sequence(t: tuple, charset: str) -> tuple: ...
205
```