1. 程式人生 > 資料庫 >Python非同步操作MySQL示例【使用aiomysql】

Python非同步操作MySQL示例【使用aiomysql】

本文例項講述了Python非同步操作MySQL。分享給大家供大家參考,具體如下:

安裝aiomysql

依賴

  • Python3.4+
  • asyncio
  • PyMySQL

安裝

pip install aiomysql

應用

基本的非同步連線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',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',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))

更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python數學運算技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》

希望本文所述對大家Python程式設計有所幫助。