aiomysql异步连接mysql

aiomysql:

  1.异步连接

  2.异步单例

import asyncio
import aiomysql

loop = asyncio.get_event_loop()


async def getconnection():

    conn = await aiomysql.connect(host="127.0.0.1", port=3306,
                                  user="root", password="root",
                                  db="mysql", loop=loop)

    if conn:
        print('connect correct')
        return conn
    else:
        raise("connect to mysql error ")
        conn.close

loop.run_until_complete(getconnection())

异步连接数据库

class Pmysql:
    """docstring for Pmydql."""
    __connection = None

    def __init__(self, ):
        self.conn = None
        self.cursor = None

    @staticmethod
    async def getconnection():
        if not Pmysql.__connection:
            conn = await aiomysql.connect(host='127.0.0.1', port=3306,
                                          user='root', password='root',
                                          db='youku')
            if conn:
                Pmysql.__connection = conn
                print('connect to mysql correct!')
                return conn
            else:
                raise("connect to mysql error ")
        else:
            return Pmysql.__connection

aiomysql异步单例版本

 

posted @ 2019-10-28 09:36  杨归元  阅读(697)  评论(0编辑  收藏  举报