Convert Figma logo to code with AI

aio-libs logoaiomysql

aiomysql is a library for accessing a MySQL database from the asyncio

1,805
259
1,805
117

Top Related Projects

7,762

MySQL client library for Python

1,408

aiopg is a library for accessing a PostgreSQL database from the asyncio

7,296

A fast PostgreSQL Database Client Library for Python/asyncio.

Familiar asyncio ORM for python, built with relations in mind

Async database support for Python. 🗄

The Database Toolkit for Python

Quick Overview

The aiomysql library is an asynchronous MySQL driver for Python, built on top of the asyncio library. It provides a simple and efficient way to interact with MySQL databases in an asynchronous environment, allowing for concurrent database operations without blocking the main event loop.

Pros

  • Asynchronous Execution: aiomysql leverages the asyncio library, enabling asynchronous database operations that do not block the main event loop, improving the overall performance and responsiveness of the application.
  • Pythonic API: The library offers a Pythonic API, making it easy to integrate with existing Python codebases and follow idiomatic Python conventions.
  • Connection Pooling: aiomysql supports connection pooling, allowing for efficient management and reuse of database connections, reducing the overhead of establishing new connections for each operation.
  • Compatibility: The library is compatible with the standard mysql-python API, making it easy to migrate existing projects that use the synchronous MySQL driver.

Cons

  • Limited Functionality: While aiomysql provides a solid foundation for interacting with MySQL databases, it may lack some advanced features or functionality compared to other MySQL drivers or ORMs (Object-Relational Mappers).
  • Dependency on asyncio: The library is tightly coupled with the asyncio library, which may not be suitable for all use cases or projects that prefer a different asynchronous framework.
  • Potential Learning Curve: Developers new to asynchronous programming or the asyncio library may face a steeper learning curve when working with aiomysql.
  • Limited Documentation: The project's documentation, while generally good, may not cover all edge cases or provide comprehensive examples for every use case.

Code Examples

Here are a few code examples demonstrating the usage of aiomysql:

  1. Connecting to a MySQL Database:
import asyncio
import aiomysql

async def connect_to_mysql():
    conn = await aiomysql.connect(
        host='localhost',
        port=3306,
        user='your_username',
        password='your_password',
        db='your_database'
    )
    return conn

async def main():
    conn = await connect_to_mysql()
    async with conn.cursor() as cur:
        await cur.execute("SELECT * FROM your_table")
        result = await cur.fetchall()
        print(result)

    conn.close()
    await conn.wait_closed()

if __:
    asyncio.run(main())
  1. Executing a Query:
async def execute_query(conn, query, params=None):
    async with conn.cursor() as cur:
        await cur.execute(query, params)
        result = await cur.fetchall()
    return result

async def main():
    conn = await connect_to_mysql()
    result = await execute_query(conn, "SELECT * FROM your_table WHERE id = %s", (1,))
    print(result)
    conn.close()
    await conn.wait_closed()

if __:
    asyncio.run(main())
  1. Performing a Transaction:
async def transaction_example(conn):
    async with conn.cursor() as cur:
        try:
            await cur.execute("START TRANSACTION")
            await cur.execute("INSERT INTO your_table (name, value) VALUES (%s, %s)", ('John Doe', 42))
            await cur.execute("INSERT INTO your_table (name, value) VALUES (%s, %s)", ('Jane Doe', 24))
            await conn.commit()
        except:
            await conn.rollback()
            raise

async def main():
    conn = await connect_to_mysql()
    await transaction_example(conn)
    conn.close()
    await conn.wait_closed()

if __:
    asyncio.run(main())

Getting Started

To get started with aiomysql, follow these steps:

  1. Install the library using pip:
pip install aiomysql
  1. Import the necessary modules and establish a connection to your MySQL database:
import asyncio

Competitor Comparisons

7,762

MySQL client library for Python

Pros of PyMySQL

  • Simpler to use for synchronous programming
  • More mature and stable, with a longer history
  • Wider adoption and community support

Cons of PyMySQL

  • Lacks native support for asynchronous operations
  • May not perform as well in high-concurrency scenarios
  • Limited compatibility with modern async frameworks

Code Comparison

PyMySQL (synchronous):

import pymysql

conn = pymysql.connect(host='localhost', user='user', password='password', database='db')
with conn.cursor() as cursor:
    cursor.execute("SELECT * FROM table")
    result = cursor.fetchall()
conn.close()

aiomysql (asynchronous):

import aiomysql

async def main():
    conn = await aiomysql.connect(host='localhost', user='user', password='password', db='db')
    async with conn.cursor() as cursor:
        await cursor.execute("SELECT * FROM table")
        result = await cursor.fetchall()
    conn.close()

The main difference is that aiomysql uses async/await syntax, allowing for non-blocking database operations in asynchronous applications. PyMySQL, on the other hand, uses a traditional synchronous approach, which is simpler but may not be as efficient in scenarios requiring high concurrency.

1,408

aiopg is a library for accessing a PostgreSQL database from the asyncio

Pros of aiopg

  • Native support for PostgreSQL-specific features and data types
  • Utilizes the psycopg2 driver, which is known for its robustness and performance
  • Offers both high-level (SAAsync) and low-level APIs for flexibility

Cons of aiopg

  • Limited to PostgreSQL databases only
  • May have a steeper learning curve for developers not familiar with PostgreSQL

Code Comparison

aiopg:

async with aiopg.create_pool(dsn) as pool:
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT * FROM users")
            result = await cur.fetchall()

aiomysql:

async with aiomysql.create_pool(host='localhost', port=3306,
                                user='root', password='', db='mysql') as pool:
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT * FROM users")
            result = await cur.fetchall()

Both libraries offer similar APIs for creating connection pools and executing queries. The main difference lies in the connection parameters and the underlying database system they support.

7,296

A fast PostgreSQL Database Client Library for Python/asyncio.

Pros of asyncpg

  • Significantly faster performance due to its custom protocol implementation
  • Native support for PostgreSQL-specific features like JSONB and arrays
  • More comprehensive type support, including custom types and enums

Cons of asyncpg

  • Limited to PostgreSQL databases only
  • Steeper learning curve due to its unique API design
  • Less compatibility with existing SQLAlchemy-based codebases

Code Comparison

asyncpg:

async with asyncpg.create_pool(dsn) as pool:
    async with pool.acquire() as conn:
        result = await conn.fetch('SELECT * FROM users')

aiomysql:

async with aiomysql.create_pool(host='localhost', port=3306,
                                user='root', password='', db='mysql') as pool:
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute('SELECT * FROM users')
            result = await cur.fetchall()

The code examples highlight the differences in API design and usage between the two libraries. asyncpg offers a more streamlined approach with fewer nested contexts, while aiomysql follows a more traditional database API structure.

Familiar asyncio ORM for python, built with relations in mind

Pros of Tortoise-ORM

  • Provides a high-level ORM with support for asyncio
  • Offers a more Pythonic and intuitive API for database operations
  • Includes built-in support for model relationships and migrations

Cons of Tortoise-ORM

  • May have a steeper learning curve for developers new to ORMs
  • Potentially slower performance for simple queries compared to raw SQL

Code Comparison

Tortoise-ORM:

from tortoise import fields, models

class User(models.Model):
    name = fields.CharField(max_length=50)
    email = fields.CharField(max_length=100)

await User.create(name="John", email="john@example.com")

aiomysql:

import aiomysql

async with aiomysql.connect(...) as conn:
    async with conn.cursor() as cur:
        await cur.execute("INSERT INTO users (name, email) VALUES (%s, %s)", ("John", "john@example.com"))
        await conn.commit()

Tortoise-ORM provides a more abstract and Pythonic approach to database operations, while aiomysql offers lower-level control and potentially better performance for simple queries. Tortoise-ORM is better suited for complex applications with intricate data models, while aiomysql might be preferred for simpler projects or when fine-grained control over SQL queries is required.

Async database support for Python. 🗄

Pros of databases

  • Supports multiple database backends (MySQL, PostgreSQL, SQLite)
  • Provides a higher-level, more Pythonic API
  • Includes query builders and result parsing

Cons of databases

  • Less mature and potentially less stable than aiomysql
  • May have fewer MySQL-specific features
  • Slightly higher learning curve due to its abstraction layer

Code Comparison

databases:

import databases

database = databases.Database("mysql://user:pass@localhost/db")

async def main():
    await database.connect()
    query = "SELECT * FROM users WHERE age > :age"
    results = await database.fetch_all(query=query, values={"age": 18})

aiomysql:

import aiomysql

async def main():
    conn = await aiomysql.connect(host='localhost', user='user', password='pass', db='db')
    async with conn.cursor() as cur:
        await cur.execute("SELECT * FROM users WHERE age > %s", (18,))
        results = await cur.fetchall()

Both libraries provide asynchronous database access, but databases offers a more abstract and flexible approach, while aiomysql provides a lower-level, MySQL-specific implementation. The choice between them depends on project requirements, such as database backend flexibility and desired API abstraction level.

The Database Toolkit for Python

Pros of SQLAlchemy

  • Comprehensive ORM support with advanced querying capabilities
  • Database-agnostic, supporting multiple database backends
  • Extensive documentation and large community support

Cons of SQLAlchemy

  • Steeper learning curve due to its complexity and feature-rich nature
  • Not natively asynchronous, requiring additional libraries for async support

Code Comparison

SQLAlchemy:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base

Base = declarative_base()
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

aiomysql:

import aiomysql

async def fetch_users():
    conn = await aiomysql.connect(host='localhost', port=3306,
                                  user='root', password='', db='mydb')
    async with conn.cursor() as cur:
        await cur.execute("SELECT * FROM users")
        result = await cur.fetchall()
    conn.close()
    return result

SQLAlchemy provides a high-level ORM abstraction, while aiomysql offers direct, asynchronous database access. SQLAlchemy is more suitable for complex applications with multiple database backends, whereas aiomysql is ideal for asynchronous MySQL-specific projects requiring low-level database interactions.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

aiomysql

.. image:: https://github.com/aio-libs/aiomysql/actions/workflows/ci-cd.yml/badge.svg?branch=master :target: https://github.com/aio-libs/aiomysql/actions/workflows/ci-cd.yml .. image:: https://codecov.io/gh/aio-libs/aiomysql/branch/master/graph/badge.svg :target: https://codecov.io/gh/aio-libs/aiomysql :alt: Code coverage .. image:: https://badge.fury.io/py/aiomysql.svg :target: https://badge.fury.io/py/aiomysql :alt: Latest Version .. image:: https://readthedocs.org/projects/aiomysql/badge/?version=latest :target: https://aiomysql.readthedocs.io/ :alt: Documentation Status .. image:: https://badges.gitter.im/Join%20Chat.svg :target: https://gitter.im/aio-libs/Lobby :alt: Chat on Gitter

aiomysql is a "driver" for accessing a MySQL database from the asyncio_ (PEP-3156/tulip) framework. It depends on and reuses most parts of PyMySQL_ . aiomysql tries to be like awesome aiopg_ library and preserve same api, look and feel.

Internally aiomysql is copy of PyMySQL, underlying io calls switched to async, basically yield from and asyncio.coroutine added in proper places)). sqlalchemy support ported from aiopg_.

Documentation

https://aiomysql.readthedocs.io/

Basic Example

aiomysql based on PyMySQL_ , and provides same api, you just need to use await conn.f() or yield from conn.f() instead of calling conn.f() for every method.

Properties are unchanged, so conn.prop is correct as well as conn.prop = val.

.. code:: python

import asyncio
import aiomysql


async def test_example(loop):
    pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
                                      user='root', password='',
                                      db='mysql', loop=loop)
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT 42;")
            print(cur.description)
            (r,) = await cur.fetchone()
            assert r == 42
    pool.close()
    await pool.wait_closed()


loop = asyncio.get_event_loop()
loop.run_until_complete(test_example(loop))

Example of SQLAlchemy optional integration

Sqlalchemy support has been ported from aiopg_ so api should be very familiar for aiopg_ user.:

.. code:: python

import asyncio
import sqlalchemy as sa

from aiomysql.sa import create_engine


metadata = sa.MetaData()

tbl = sa.Table('tbl', metadata,
               sa.Column('id', sa.Integer, primary_key=True),
               sa.Column('val', sa.String(255)))


async def go(loop):
    engine = await create_engine(user='root', db='test_pymysql',
                                 host='127.0.0.1', password='', loop=loop)
    async with engine.acquire() as conn:
        await conn.execute(tbl.insert().values(val='abc'))
        await conn.execute(tbl.insert().values(val='xyz'))

        async for row in conn.execute(tbl.select()):
            print(row.id, row.val)

    engine.close()
    await engine.wait_closed()


loop = asyncio.get_event_loop()
loop.run_until_complete(go(loop))

Requirements

  • Python_ 3.7+
  • PyMySQL_

.. _Python: https://www.python.org .. _asyncio: http://docs.python.org/3.5/library/asyncio.html .. _aiopg: https://github.com/aio-libs/aiopg .. _PyMySQL: https://github.com/PyMySQL/PyMySQL .. _Tornado-MySQL: https://github.com/PyMySQL/Tornado-MySQL