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

系统 1319 0

本文实例讲述了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', 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))


          

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论