orm,即Object Relational Mapping,全称对象关系映射。简单来说就是将数据库中的表,字段,行,与我们的面向对象编程中的类,类的属性,以及对象建立一一对应的映射关系,这样我们便可以避免直接操作数据库,而只要调用相应的方法就可以了。
1.创建数据库连接池
#异步协程:创建数据库连接池
@asyncio.coroutine
def create_pool(loop,**kw):
logging.info('start creating database connection pool')
global __pool
#yield from 调用协程函数并返回结果
__pool = yield from aiomysql.create_pool(
#kw.get(key,default):通过key在kw中查找对应的value,如果没有则返回默认值default
host = kw.get('host','localhost'),
port = kw.get('port',3306),
user = kw['user'],
password = kw['password'],
db = kw['db'],
charset = kw.get('charset','utf8'),
autocommit = kw.get('autocommit',True),
maxsize = kw.get('maxsize',10),
minsize = kw.get('minsize',1),
loop = loop
)
2.封装select方法
@asyncio.coroutine
def select(sql,args,size=None):
log(sql,args)
global __pool
#yield from从连接池返回一个连接
with (yield from __pool) as conn:
cur = yield from conn.cursor(aiomysql.DictCursor)
#执行sql语句前,先将sql语句中的占位符?换成mysql中采用的占位符%s
yield from cur.execute(sql.replace('?','%s'),args)
#size表示要返回的结果数,若为None则返回全部查询结果
if size:
rs = yield from cur.fetchmany(size)
else:
rs = yield from cur.fetchall()
yield from cur.close()
logging.info('%s rows have returned' % len(rs))
return rs
3.封装execute方法(update,insert,delete语句操作参数一样,返回影响的行数,直接封装成一个通用的执行函数)
async def execute(sql, args, autocommit=True):
log(sql)
async with __pool.get() as conn:
if not autocommit:
await conn.begin()
try:
async with conn.cursor(aiomysql.DictCursor) as cur:
await cur.