aiomysql异步数据库

发布于 2021-01-19  929 次阅读


前言

前面使用aiohttp+asyncio实现了异步爬虫,但对于数据存储还是常规的pymysql去进行连接和保存数据。本篇文章测试异步数据库aiomysql的功能和使用,去改写前面人人美剧连接项目中的数据库保存部分

aiomysql

aiomysql的数据库连接主要分为

  • conn = await aiomysql.connect(相关数据库信息)
    直接连接和pymysql.connect方法一样,而且该方法允许异步执行,所以在使用时要使用await关键字。
  • pool = await aiomysql.create_pool(相关数据库信息)
    创建一个数据库异步连接池pool,能保证数据库的长时间连接,不必再频繁的链接数据库

直接连接

在保存数据时,我们通常都是循环遍历保存,如果在循环内连接数据库,每保存一条数据就要连接一次数据库,相当耗时

# 循环保存数据
for i in range(len(magnet)):
    conn = await aiomysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='...',
        db='美剧迅雷链接')
    title_ji = title + '-第{}集'.format(i + 1)
    sql = 'insert into {table}(title,link) values(%s,%s)'.format(table='异步')
    args = (title_ji, magnet[i])

    cursor = await conn.cursor()
    await cursor.execute(sql, args=args)
    print(title_ji, cursor.rowcount)
    # 必须调用 commit, 操作才会真正在数据库中执行。
    await conn.commit()
    conn.close()

创建异步连接池

在保存数据时,我们通常都是循环遍历保存,如果在循环外连接数据库,要是循环时间太长链接失效就会报pymysql.err.InterfaceError: (0, '')的错误,所以建议在for循环外建立一个异步连接池保持连接。

pool = await aiomysql.create_pool(host='127.0.0.1', port=3306,
user='root',     password='...',
db='美剧迅雷链接', loop=loop, autocommit=True,charset='utf8')
    # 循环保存数据
    for i in range(len(magnet)):
       await soucre(i,title,magnet,pool)

async def soucre(i,title,magnet,pool):
    # ==================异步连接池 pool============
    title_ji = title + '-第{}集'.format(i + 1)
    sql = 'insert into {table}(title,link) values(%s,%s)'.format(table='异步')
    args = (title_ji, magnet[i])
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            # await cur.execute("SELECT 42;")
            await cur.execute(sql,args)
    print(title_ji,cur.rowcount)


所念皆星河