async_mysql.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """
  2. @author: luojunhui
  3. """
  4. import aiomysql
  5. class AsyncMySQLClient(object):
  6. """
  7. Async MySQL
  8. """
  9. def __init__(self, app):
  10. self.app = app
  11. async def init_pool(self):
  12. """
  13. 初始化连接
  14. :return:
  15. """
  16. self.app.mysql_pool = await aiomysql.create_pool(
  17. host='rm-bp1159bu17li9hi94.mysql.rds.aliyuncs.com',
  18. port=3306,
  19. user='crawler',
  20. password='crawler123456@',
  21. db='piaoquan-crawler',
  22. charset='utf8mb4'
  23. )
  24. print("数据库初始化完成......")
  25. async def close_pool(self):
  26. """
  27. 关闭 mysql 连接
  28. :return:
  29. """
  30. self.app.mysql_pool.close()
  31. await self.app.mysql_pool.wait_closed()
  32. async def select(self, sql):
  33. """
  34. select method
  35. :param sql:
  36. :return:
  37. """
  38. async with self.app.mysql_pool.acquire() as conn:
  39. async with conn.cursor() as cursor:
  40. await cursor.execute(sql)
  41. result = await cursor.fetchall()
  42. return result
  43. async def async_insert(self, sql, params):
  44. """
  45. insert and update method
  46. :param params:
  47. :param sql:
  48. :return:
  49. """
  50. async with self.app.mysql_pool.acquire() as coon:
  51. async with coon.cursor() as cursor:
  52. await cursor.execute(sql, params)
  53. await coon.commit()