mysql_operate.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import time
  2. import pymysql
  3. from config import mysqldb, log_msg
  4. # 数据库查询函数
  5. def mysql_operate(sql, insert_list=None, operate_flag=0):
  6. # 建立链接
  7. mysql_conn = pymysql.connect(
  8. host=mysqldb["host"],
  9. user=mysqldb["user"],
  10. password=mysqldb["password"],
  11. db=mysqldb["db"],
  12. charset=mysqldb["charset"],
  13. cursorclass=pymysql.cursors.DictCursor
  14. )
  15. # 查询返回字典
  16. res_dict = dict()
  17. # 创建游标对象cursor
  18. cursor = mysql_conn.cursor()
  19. # 判断mysql查询和插入/删除标志
  20. if operate_flag == 0:
  21. # 执行sql语句
  22. cursor.execute(sql)
  23. res_dict = cursor.fetchone()
  24. else:
  25. try:
  26. # 执行sql语句
  27. if insert_list is not None:
  28. cursor.executemany(sql, insert_list)
  29. else:
  30. cursor.execute(sql)
  31. # 提交事务
  32. mysql_conn.commit()
  33. except Exception as e:
  34. print(e)
  35. # 如果出现异常,回滚
  36. mysql_conn.rollback()
  37. print(log_msg.format(id=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
  38. type="mysql操作",
  39. message="mysql数据操作失败"))
  40. # 关闭数据库连接
  41. cursor.close()
  42. mysql_conn.close()
  43. return res_dict