溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Python怎么實現(xiàn)異步操作MySQL

發(fā)布時間:2021-04-14 17:31:00 來源:億速云 閱讀:938 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹使用Python怎么實現(xiàn)異步操作MySQL,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

安裝aiomysql

依賴

  • Python3.4+

  • asyncio

  • PyMySQL

安裝

pip install aiomysql

應(yīng)用

基本的異步連接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))

對象關(guān)系映射SQLAlchemy - Object Relationship Mapping

可以隨意定義表結(jié)構(gòu),輕松調(diào)用查詢、插入等操作方法。

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

關(guān)于使用Python怎么實現(xiàn)異步操作MySQL就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI