使用aiomysql接口封装一个数据库的类。包含创建表更新数据查询数据插入数据等接口。-请用Python表示
import asyncio import aiomysql
class MySQLDB: def init(self, host, port, user, password, db): self.host = host self.port = port self.user = user self.password = password self.db = db
async def create_table(self, table_name, columns):
async with aiomysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
db=self.db
) as conn:
async with conn.cursor() as cur:
await cur.execute(f"CREATE TABLE {table_name} ({columns})")
async def update(self, table_name, set_values, where_clause):
async with aiomysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
db=self.db
) as conn:
async with conn.cursor() as cur:
sql = f"UPDATE {table_name} SET {set_values} WHERE {where_clause}"
await cur.execute(sql)
async def select(self, table_name, columns, where_clause=None):
async with aiomysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
db=self.db
) as conn:
async with conn.cursor(aiomysql.DictCursor) as cur:
sql = f"SELECT {columns} FROM {table_name}"
if where_clause:
sql += f" WHERE {where_clause}"
await cur.execute(sql)
rows = await cur.fetchall()
return rows
async def insert(self, table_name, values):
async with aiomysql.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
db=self.db
) as conn:
async with conn.cursor() as cur:
sql = f"INSERT INTO {table_name} VALUES ({values})"
await cur.execute(sql)
await conn.commit()
原文地址: https://www.cveoy.top/t/topic/ggi 著作权归作者所有。请勿转载和采集!