class MysqlOptAsync(object):
def __init__(self, loop):
self.host = host
self.port = port
self.user = username
self.password = password
self.db = database
self._pool = None
self._loop = loop
# self._pool = None
async def pool(self):
if not self._pool:
print('开始生成链接池')
self._pool = await aiomysql.create_pool(host=self.host, port=self.port, user=self.user,password=self.password, db=self.db, loop=self._loop)
print(self._pool)
return self._pool
async def insertOpt(self, data=None):
async with self._pool.acquire() as conn:
async with conn.cursor() as cur:
sql = 'insert into test_asyncio(age) value(%s);'
try:
await cur.execute(sql, data)
await conn.commit()
except Exception as e:
print(e)
await conn.rollback()
# await cur.commit()
# print(await cur.last_id())
if __name__ == '__main__':
async def insert_data(obj_str=None):
for i in range(21, 40):
await obj_str.insertOpt(data=(i,))
async def main(loop):
mysql = MysqlOptAsync(loop=loop)
await mysql.pool()
await insert_data(obj_str=mysql)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
数据库的异步操作,aiomysql
最新推荐文章于 2024-04-26 14:29:42 发布