SoFunction
Updated on 2025-03-01

Python asynchronous operation MySQL example [Use aiomysql]

This article describes the asynchronous operation of MySQL in Python. Share it for your reference, as follows:

Install aiomysql

rely

  • Python3.4+
  • asyncio
  • PyMySQL

Install

pip install aiomysql

application

Basic asynchronous 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 () as conn:
      async with () as cur:
        await ("SELECT 42;")
        value = await ()
        print(value)
loop.run_until_complete(go())

Asynchronous connection 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 () as conn:
    async with () as cur:
      await ("SELECT 42;")
      print()
      (r,) = await ()
      assert r == 42
  ()
  await pool.wait_closed()
loop = asyncio.get_event_loop()
loop.run_until_complete(test_example(loop))

Object Relationship Mapping SQLAlchemy - Object Relationship Mapping

You can define the table structure at will and easily call operation methods such as query and insertion.

import asyncio
import sqlalchemy as sa
from  import create_engine
metadata = ()
tbl = ('tbl', metadata,
        ('id', , primary_key=True),
        ('val', (255)))
async def go(loop):
  engine = await create_engine(user='root', db='test_pymysql',
                 host='127.0.0.1', password='', loop=loop)
  async with () as conn:
    await (().values(val='abc'))
    await (().values(val='xyz'))
    async for row in (()):
      print(, )
  ()
  await engine.wait_closed()
loop = asyncio.get_event_loop()
loop.run_until_complete(go(loop))

For more information about Python-related content, please check out the topic of this site:Summary of common Python database operation skills》、《Summary of Python mathematical operation skills》、《Python data structure and algorithm tutorial》、《Summary of Python function usage tips》、《Summary of Python string operation skills》、《Python introduction and advanced classic tutorials"and"Summary of Python file and directory operation skills

I hope this article will be helpful to everyone's Python programming.