asyncMySQL.py 1.5 KB

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