mysql.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """
  2. Mysql Functions
  3. """
  4. import pymysql
  5. class MysqlClient(object):
  6. """
  7. MySQL工具, env默认prod版本
  8. """
  9. def __init__(self):
  10. mysql_config = {
  11. "host": "rm-bp1159bu17li9hi94.mysql.rds.aliyuncs.com",
  12. "port": 3306, # 端口号
  13. "user": "crawler", # mysql用户名
  14. "passwd": "crawler123456@", # mysql用户登录密码
  15. "db": "piaoquan-crawler", # 数据库名
  16. "charset": "utf8mb4" # 如果数据库里面的文本是utf8编码的,charset指定是utf8
  17. }
  18. self.connection = pymysql.connect(
  19. host=mysql_config['host'], # 数据库IP地址,内网地址
  20. port=mysql_config['port'], # 端口号
  21. user=mysql_config['user'], # mysql用户名
  22. passwd=mysql_config['passwd'], # mysql用户登录密码
  23. db=mysql_config['db'], # 数据库名
  24. charset=mysql_config['charset'] # 如果数据库里面的文本是utf8编码的,charset指定是utf8
  25. )
  26. def select(self, sql):
  27. """
  28. 查询
  29. :param sql:
  30. :return:
  31. """
  32. cursor = self.connection.cursor()
  33. cursor.execute(sql)
  34. data = cursor.fetchall()
  35. return data
  36. def update(self, sql):
  37. """
  38. 插入
  39. :param sql:
  40. :return:
  41. """
  42. cursor = self.connection.cursor()
  43. try:
  44. res = cursor.execute(sql)
  45. self.connection.commit()
  46. return res
  47. except Exception as e:
  48. self.connection.rollback()
  49. def close(self):
  50. """
  51. 关闭连接
  52. """
  53. self.connection.close()