Quick start¶
Install¶
The wheels need nothing else installed: no libmysqlclient, no compiler. See Installation for the platforms and versions covered.
Connect and query¶
rustmy follows PEP 249, the DB-API, as
mysqlclient and PyMySQL do: connect(), cursors, %s placeholders, and
explicit commits.
import rustmy
with rustmy.connect(
host="localhost", user="app", password="secret", database="shop"
) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT id, name, price FROM products WHERE price < %s", (10,))
for product_id, name, price in cursor:
print(product_id, name, price)
cursor.executemany(
"INSERT INTO products (name, price) VALUES (%s, %s)",
[("tea", 3.5), ("coffee", 4.2)],
)
conn.commit() # (1)!
- Autocommit is off by default, as PEP 249 asks: without
commit()the inserts are rolled back when the connection closes. Passautocommit=Truetoconnect()to commit every statement.
Leaving the with block closes the connection. Parameters are always passed
separately from the SQL: rustmy escapes them for the connection's character
set and SQL mode.
Rows as dictionaries¶
from rustmy.cursors import DictCursor
with conn.cursor(DictCursor) as cursor:
cursor.execute("SELECT id, name FROM products ORDER BY id LIMIT 2")
print(cursor.fetchall()) # ({'id': 1, 'name': 'tea'}, {'id': 2, 'name': 'coffee'})
asyncio¶
rustmy.aio runs the same driver on the event loop, with the API of
aiomysql and asyncmy:
import asyncio
from rustmy import aio
async def main() -> None:
async with aio.connect(
host="localhost", user="app", password="secret", database="shop"
) as conn:
async with conn.cursor(aio.DictCursor) as cursor:
await cursor.execute("SELECT id, name FROM products WHERE id = %s", (42,))
print(await cursor.fetchone())
asyncio.run(main())
SQLAlchemy and Django¶
The mysql+rustmy (or mariadb+rustmy) URL, nothing to import:
Next steps¶
-
Connecting, queries, cursors, TLS, asyncio, pools and running in production.
-
What changes coming from mysqlclient, PyMySQL, aiomysql or asyncmy.
-
Every class, function and argument.
-
The benchmarks against the other drivers.