本文實例講述了python異步操作mysql。分享給大家供大家參考,具體如下:
安裝aiomysql
依賴
- python3.4+
- asyncio
- pymysql
安裝
1
|
pip install aiomysql |
應用
基本的異步連接connection
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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
可以隨意定義表結構,輕松調用查詢、插入等操作方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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程序設計有所幫助。
原文鏈接:https://blog.csdn.net/ydyang1126/article/details/78226701