Python异步操作MySQL示例【使用aiomysql】
本文实例讲述了Python异步操作MySQL。分享给大家供大家参考,具体如下:
安装aiomysql
依赖
- Python3.4+
- asyncio
- PyMySQL
安装
pipinstallaiomysql
应用
基本的异步连接connection
importasyncio
fromaiomysqlimportcreate_pool
loop=asyncio.get_event_loop()
asyncdefgo():
asyncwithcreate_pool(host='127.0.0.1',port=3306,
user='root',password='',
db='mysql',loop=loop)aspool:
asyncwithpool.get()asconn:
asyncwithconn.cursor()ascur:
awaitcur.execute("SELECT42;")
value=awaitcur.fetchone()
print(value)
loop.run_until_complete(go())
异步的连接池pool
importasyncio
importaiomysql
asyncdeftest_example(loop):
pool=awaitaiomysql.create_pool(host='127.0.0.1',port=3306,
user='root',password='',
db='mysql',loop=loop)
asyncwithpool.acquire()asconn:
asyncwithconn.cursor()ascur:
awaitcur.execute("SELECT42;")
print(cur.description)
(r,)=awaitcur.fetchone()
assertr==42
pool.close()
awaitpool.wait_closed()
loop=asyncio.get_event_loop()
loop.run_until_complete(test_example(loop))
对象关系映射SQLAlchemy-ObjectRelationshipMapping
可以随意定义表结构,轻松调用查询、插入等操作方法。
importasyncio
importsqlalchemyassa
fromaiomysql.saimportcreate_engine
metadata=sa.MetaData()
tbl=sa.Table('tbl',metadata,
sa.Column('id',sa.Integer,primary_key=True),
sa.Column('val',sa.String(255)))
asyncdefgo(loop):
engine=awaitcreate_engine(user='root',db='test_pymysql',
host='127.0.0.1',password='',loop=loop)
asyncwithengine.acquire()asconn:
awaitconn.execute(tbl.insert().values(val='abc'))
awaitconn.execute(tbl.insert().values(val='xyz'))
asyncforrowinconn.execute(tbl.select()):
print(row.id,row.val)
engine.close()
awaitengine.wait_closed()
loop=asyncio.get_event_loop()
loop.run_until_complete(go(loop))
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。