1. 程式人生 > >python非同步操作MySQL(aiomysql)

python非同步操作MySQL(aiomysql)

aiomysql是用於從asyncio(PEP-3156 / tulip)框架訪問MySQL資料庫的“驅動程式”。 它依賴並重用了PyMySQL的大部分內容。 aiomysql試圖成為類aiopg的庫,並保留相同的api、外觀和感覺。
內部的aiomysql是PyMySQL的副本,底層的io呼叫切換到async,基本上是在適當的地方產生和asyncio.coroutine。 sqlalchemy支援從aiopg移植。
文件https://aiomysql.readthedocs.io/

基本的非同步connection

import asyncio
from aiomysql import
create_pool loop = asyncio.get_event_loop() async def go(): async with create_pool(host='127.0.0.1', port=3306, user='root', password='', db='mysql', loop=loop) as pool: async with pool.get() as conn: async with conn.cursor() as
cur: await cur.execute("SELECT 42;") value = await cur.fetchone() print(value) loop.run_until_complete(go())

連線 pool

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))

物件關係對映SQLAlchemy - Object Relationship Mapping

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))