async_mysql.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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, params):
  45. """
  46. insert and update method
  47. :param params:
  48. :param sql:
  49. :return:
  50. """
  51. async with self.app.mysql_pool.acquire() as coon:
  52. async with coon.cursor() as cursor:
  53. await cursor.execute(sql, params)
  54. await coon.commit()