Guest User

Untitled

a guest
Feb 18th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. class MySQLCursor:
  2. """创建一个游标类"""
  3.  
  4. def __init__(self,cursor,logger):
  5. self.cursor=cursor
  6. self.logger=logger
  7.  
  8. def execute(self,sql,params=None):
  9. self.logger.info(sql+str(params))
  10. self.cursor.execute(sql, params)
  11. self.cursor.execute("select last_insert_id()")
  12. res = self.cursor.fetchone()
  13. if len(res)==1:
  14. if type(res)==type({}):
  15. return res['last_insert_id()']
  16. if type(res)==type(()):
  17. return res[0]
  18. return 0
  19.  
  20. def query(self,sql,params=None,with_description=False):
  21. self.logger.info(sql+str(params))
  22. self.cursor.execute(sql, params)
  23. rows = self.cursor.fetchall()
  24. if with_description:
  25. res = rows, self.cursor.description
  26. else:
  27. res = rows
  28. return res
  29.  
  30. class MySQLInstance:
  31. """创建一个实例类"""
  32.  
  33. def __init__(self,host,port,username,password,schema=None,
  34. charset='utf8',dict_result=False,logger=None):
  35. self.host=host
  36. self.port=port
  37. self.username=username
  38. self.password=password
  39. self.schema=schema
  40. self.charset=charset
  41. self.dict_result=dict_result
  42. if logger is None:
  43. logger=logging.getLogger(__name__)
  44. self.logger=logger
  45.  
  46. def __enter__(self):
  47. self.con=pymysql.connect(host=self.host,port=self.port,user=self.username,
  48. password=self.password,charset=self.charset,db=self.schema)
  49. if self.dict_result:
  50. self.cursor=self.con.cursor(pymysql.cursors.DictCursor)
  51. else:
  52. self.cursor=self.con.cursor()
  53. return MySQLCursor(self.cursor,self.logger)
  54. def __exit__(self,exc_type, exc_value, exc_tb):
  55. self.cursor.execute("commit")
  56. self.cursor.close()
  57. self.con.close()
Add Comment
Please, Sign In to add comment