async_mysql.py 1.4 KB

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