Skip to content

Instantly share code, notes, and snippets.

@Trim21 Trim21/bgmine.user.sql
Last active Mar 20, 2019

Embed
What would you like to do?
create table bgmine.user
(
id int auto_increment
primary key,
username varchar(80) null,
email varchar(120) null,
constraint email
unique (email),
constraint username
unique (username)
);
import asyncio
import aiomysql
class AioMysqlHelper:
pool = None
@classmethod
async def get_pool(cls):
if not cls.pool:
cls.pool = await aiomysql.create_pool(
db='bgmine',
host='127.0.0.1',
port=3306,
user='root',
password='',
)
return cls.pool
@classmethod
async def insert(cls, sql, params=None):
params = params or []
async with cls.pool.acquire() as conn:
async with conn.cursor() as cur:
try:
await cur.execute(sql, params)
await cur.execute("commit;")
await conn.commit()
except Exception as err:
await conn.rollback()
raise err
@classmethod
async def select(cls, sql, params=None, one=True):
params = params or []
async with cls.pool.acquire() as conn:
async with conn.cursor() as cur:
try:
await cur.execute(sql, params)
return await (cur.fetchone() if one else cur.fetchall())
except Exception as err:
conn.rollback()
raise err
async def main():
await AioMysqlHelper.get_pool()
await AioMysqlHelper.insert("""
INSERT INTO `bgmine`.`user` (`username`, `email`) VALUES ('7', '7')
""")
await AioMysqlHelper.insert("""
INSERT INTO `bgmine`.`user` (`username`, `email`) VALUES ('8', '8')
""")
x = await AioMysqlHelper.select("""
SELECT t.* FROM bgmine.user t
""", one=False)
print(x)
await AioMysqlHelper.insert("""
INSERT INTO `bgmine`.`user` (`username`, `email`) VALUES ('9', '9')
""")
x = await AioMysqlHelper.select("""
SELECT t.* FROM bgmine.user t
""", one=False)
print(x)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.