asyncMySQL.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. connect_timeout=120,
  24. )
  25. print("mysql init successfully")
  26. async def close_pool(self):
  27. """
  28. 关闭 mysql 连接
  29. :return:
  30. """
  31. self.app.mysql_pool.close()
  32. await self.app.mysql_pool.wait_closed()
  33. async def async_select(self, sql):
  34. """
  35. select method
  36. :param sql:
  37. :return:
  38. """
  39. async with self.app.mysql_pool.acquire() as conn:
  40. async with conn.cursor() as cursor:
  41. await cursor.execute(sql)
  42. result = await cursor.fetchall()
  43. return result
  44. async def async_insert(self, sql):
  45. """
  46. insert and update method
  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)
  53. await coon.commit()