mysqlhelper.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # author:SunXiuWen
  4. # make_time:2019/1/13
  5. import pymysql
  6. from DBUtils.PooledDB import PooledDB
  7. import db_config as config
  8. """
  9. @功能:创建数据库连接池
  10. """
  11. class MyConnectionPool(object):
  12. __pool = None
  13. # 创建数据库连接conn和游标cursor
  14. def __enter__(self):
  15. self.conn = self.__getconn()
  16. self.cursor = self.conn.cursor()
  17. # 创建数据库连接池
  18. def __getconn(self):
  19. if self.__pool is None:
  20. self.__pool = PooledDB(
  21. creator=config.DB_CREATOR,
  22. mincached=config.DB_MIN_CACHED,
  23. maxcached=config.DB_MAX_CACHED,
  24. maxshared=config.DB_MAX_SHARED,
  25. maxconnections=config.DB_MAX_CONNECYIONS,
  26. blocking=config.DB_BLOCKING,
  27. maxusage=config.DB_MAX_USAGE,
  28. setsession=config.DB_SET_SESSION,
  29. host=config.DB_TEST_HOST,
  30. port=config.DB_TEST_PORT,
  31. user=config.DB_TEST_USER,
  32. passwd=config.DB_TEST_PASSWORD,
  33. db=config.DB_TEST_DBNAME,
  34. use_unicode=True,
  35. charset=config.DB_CHARSET
  36. )
  37. return self.__pool.connection()
  38. # 释放连接池资源
  39. def __exit__(self, exc_type, exc_val, exc_tb):
  40. self.cursor.close()
  41. self.conn.close()
  42. # 从连接池中取出一个连接
  43. def getconn(self):
  44. conn = self.__getconn()
  45. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  46. return cursor, conn
  47. """执行语句查询有结果返回结果没有返回0;增/删/改返回变更数据条数,没有返回0"""
  48. class MySqLHelper(object):
  49. def __init__(self):
  50. self.db = MyConnectionPool() # 从数据池中获取连接
  51. def __new__(cls, *args, **kwargs):
  52. if not hasattr(cls, 'inst'): # 单例
  53. cls.inst = super(MySqLHelper, cls).__new__(cls, *args, **kwargs)
  54. return cls.inst
  55. # 封装执行命令
  56. def execute(self, sql, param=None, autoclose=False):
  57. """
  58. 【主要判断是否有参数和是否执行完就释放连接】
  59. :param sql: 字符串类型,sql语句
  60. :param param: sql语句中要替换的参数"select %s from tab where id=%s" 其中的%s就是参数
  61. :param autoclose: 是否关闭连接
  62. :return: 返回连接conn和游标cursor
  63. """
  64. cursor, conn = self.db.getconn() # 从连接池获取连接
  65. count = 0
  66. try:
  67. # count : 为改变的数据条数
  68. if param:
  69. count = cursor.execute(sql, param)
  70. else:
  71. count = cursor.execute(sql)
  72. conn.commit()
  73. if autoclose:
  74. self.close(cursor, conn)
  75. except Exception as e:
  76. print("db error_msg:", e.args)
  77. return cursor, conn, count
  78. # 释放连接
  79. def close(self, cursor, conn):
  80. """释放连接归还给连接池"""
  81. cursor.close()
  82. conn.close()
  83. # 查询所有
  84. def selectall(self, sql, param=None):
  85. try:
  86. cursor, conn, count = self.execute(sql, param)
  87. res = cursor.fetchall()
  88. return res
  89. except Exception as e:
  90. print("db error_msg:", e.args)
  91. self.close(cursor, conn)
  92. return count
  93. # 查询单条
  94. def selectone(self, sql, param=None):
  95. try:
  96. cursor, conn, count = self.execute(sql, param)
  97. res = cursor.fetchone()
  98. self.close(cursor, conn)
  99. return res
  100. except Exception as e:
  101. print("db error_msg:", e.args)
  102. self.close(cursor, conn)
  103. return count
  104. # 增加
  105. def insertone(self, sql, param):
  106. try:
  107. cursor, conn, count = self.execute(sql, param)
  108. conn.commit()
  109. self.close(cursor, conn)
  110. return count
  111. except Exception as e:
  112. print("db error_msg:", e.args)
  113. conn.rollback()
  114. self.close(cursor, conn)
  115. return count
  116. # 删除
  117. def delete(self, sql, param=None):
  118. try:
  119. cursor, conn, count = self.execute(sql, param)
  120. conn.commit()
  121. self.close(cursor, conn)
  122. return count
  123. except Exception as e:
  124. print("db error_msg:", e.args)
  125. conn.rollback()
  126. self.close(cursor, conn)
  127. return count
  128. # 修改
  129. def update(self, sql, param=None):
  130. try:
  131. cursor, conn, count = self.execute(sql, param)
  132. conn.commit()
  133. self.close(cursor, conn)
  134. return count
  135. except Exception as e:
  136. print("db error_msg:", e.args)
  137. conn.rollback()
  138. self.close(cursor, conn)
  139. return count
  140. if __name__ == '__main__':
  141. db = MySqLHelper()
  142. while True:
  143. sql1 = 'select * from space where unit=%s'
  144. args = '2'
  145. ret = db.selectone(sql=sql1, param=args)
  146. print(ret) # (79, 2, 1, 2.2, None, 2, 1)
  147. # 查询单条
  148. sql1 = 'select * from space where unit=%s'
  149. args = '2'
  150. ret = db.selectone(sql=sql1, param=args)
  151. print(ret) # (79, 2, 1, 2.2, None, 2, 1)
  152. #查询所有
  153. sql2 = "select * from space"
  154. ret = db.selectall(sql=sql2)
  155. print(ret)
  156. # 增加
  157. sql3 = 'insert into vehicle (car_number,primary_key) VALUES (%s,%s)'
  158. ret = db.insertone(sql3, ('鄂A6X3B0','DASDASDEFDFSDASDADASDAS'))
  159. print(ret)
  160. # 删除
  161. sql4 = 'delete from vehicle WHERE car_number=%s'
  162. args = '鄂A6X3B0'
  163. ret = db.delete(sql4, args)
  164. print(ret)
  165. # 修改
  166. sql5 = 'update command_queue set export_id=%s WHERE car_number LIKE %s'
  167. args = ('100', 'WK0001')
  168. ret = db.update(sql5, args)
  169. print(ret)