aiomysql icon indicating copy to clipboard operation
aiomysql copied to clipboard

Syntactic sugar for aiomysql

Open atitoff opened this issue 6 years ago • 1 comments

I successfully use your library in several projects. I propose a solution to simplify the work with the library.

import asyncio
from CshLib.conn import MySQL


class MySQLModules(MySQL):
    user = 'stat'
    password = 'bh0020'
    db = 'modules'


async def test():
    async with MySQLModules() as conn:
        async with conn.cursor() as cur:
            await cur.execute("SELECT Count(*) FROM modules.modules;")
            records = await cur.fetchone()
    print(records)


asyncio.run(test())

MySQL class code

import aiomysql


class MySQL:
    host = '127.0.0.1'
    port = 3306
    user = ''
    password = ''
    db = ''

    async def __aenter__(self) -> aiomysql.connection:
        self.conn = await aiomysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            db=self.db
        )
        return self.conn

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        self.conn.close()

atitoff avatar Feb 12 '19 17:02 atitoff

GitMate.io thinks possibly related issues are https://github.com/aio-libs/aiomysql/issues/158 (aiomysql enabled cache?), https://github.com/aio-libs/aiomysql/issues/381 (how to import aiomysql errors), https://github.com/aio-libs/aiomysql/issues/286 (Remove a connection from aiomysql.Pool), https://github.com/aio-libs/aiomysql/issues/159 (how to use aiomysql with tornado?), and https://github.com/aio-libs/aiomysql/issues/303 (aiomysql Import Error _scramble).

aio-libs-bot avatar Feb 12 '19 17:02 aio-libs-bot