Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.48 KB | None | 0 0
  1. import pymysql.cursors
  2. import configparser
  3. #连接配置信息示例
  4. config = {
  5. 'host':'localhost',
  6. 'port':3306,
  7. 'user':'root',
  8. 'password':'123',
  9. 'db':'nsbd',
  10. 'charset':'utf8mb4',
  11. 'cursorclass':pymysql.cursors.DictCursor,
  12. }
  13. class Sql:
  14. '''Conn模块中的Sql类是搭配DataSource类使用的,此类做连接实例对象'''
  15. def __init__(self, conf = None, conn_pool = None):
  16. '''conf是接收从DataSource传递过来的配置参数,conn_pool是接收传递过来的连接池'''
  17. if not isinstance(conn_pool, DataSource):
  18. raise Exception('请配置连接池给连接实例')
  19. else:
  20. self.conn_list = conn_pool.conn_list
  21. self.config = conf
  22. self.connection = pymysql.connect(**self.config)
  23. def close(self):
  24. '''打开一个连接后的关闭连接操作'''
  25. self.conn_list.append(self)#把操作完成的连接实例在追加到连接池的末尾
  26. def __createPybean(self, class_path):
  27. path_list = class_path.split('.')
  28. module_name = path_list[-2] # 模块名
  29. class_name = path_list[-1] # 类名
  30. p_m_name = '.'.join(path_list[:-1]) # 包名并模块名
  31. module = __import__(p_m_name, fromlist=module_name)
  32. return getattr(module, class_name)()
  33. def __reflectToBean(self, data_dict, class_path):
  34. '''data_dict是数据字典,class_path是要映射到类名的路径'''
  35. bean = self.__createPybean(class_path)#动态生成该类
  36. bean_attr = bean.__dict__#该类的bean属性
  37. for key in list(data_dict.keys()):
  38. if ('_' + class_path.split('.')[-1] + '__' + key in bean_attr.keys()):
  39. getattr(bean, 'set' + key.capitalize())(data_dict[key])#获取bean的set方法
  40. else:
  41. raise Exception('属性映射失败,请确保取得的数据库表中列名与pybean的属性名一致')
  42. return bean
  43. def query(self, sql, argvs = None, class_path = None):
  44. '''查询'''
  45. global result
  46. try:
  47. with self.connection.cursor() as cursor:
  48. if argvs==0:
  49. cursor.execute(sql)
  50. else:
  51. cursor.execute(sql, argvs)
  52. result = cursor.fetchall()
  53. if(class_path!=None):
  54. list = result
  55. result = []
  56. for item in list:
  57. result.append(self.__reflectToBean(item, class_path))#进行对象映射
  58. self.connection.commit()
  59. finally:
  60. return result
  61. def insert(self, sql, argvs = None):
  62. try:
  63. with self.connection.cursor() as cursor:
  64. if len(argvs) == 0:
  65. cursor.execute(sql)
  66. else:
  67. cursor.execute(sql, argvs)
  68. self.connection.commit()
  69. except:
  70. self.connection.rollback()
  71. def update(self, sql, argvs = None):
  72. self.insert(sql, argvs)
  73. def delete(self, sql, argvs = None):
  74. self.insert(sql, argvs)
  75. def __del__(self):
  76. self.connection.close()
  77. class DataSource:
  78. def __init__(self, conf, max_conn_counts = 5):
  79. '''max_conn_count是最大连接数,conf是连接数据库的基本配置,它可以是一个字典类型也可以是一个配置文件名,
  80. 若是配置文件名,则配置文件中的session名必须为‘[db]’详细参考ConfigParser模块的使用'''
  81. print('正在初始化连接池...')
  82. if isinstance(conf, dict):
  83. self.conf = conf
  84. elif isinstance(conf, str):
  85. print('正在读取DB配置文件...')
  86. self.conf = {}
  87. self.__readConfFile(conf)
  88. else:
  89. raise Exception('conf参数必须为dict或str类型')
  90. if not isinstance(max_conn_counts, int):
  91. raise Exception("最大连接数必须为int型")
  92. elif max_conn_counts not in range(1,11):#连接数介于1-10之间
  93. raise Exception("最大连接数必须介于1-10之间")
  94. else:
  95. print('连接池初始化连接开始...')
  96. #连接池的存储连接列表
  97. self.conn_list = []
  98. for i in range(0, max_conn_counts):
  99. self.conn_list.append(Sql(conf = self.conf, conn_pool = self))
  100. print('连接池初始化连接结束...')
  101. def __readConfFile(self, filePath):
  102. cp = configparser.ConfigParser()
  103. cp.read(filePath, encoding='utf-8')#编码设置为utf-8
  104. self.conf['host'] = cp.get('db', 'host')
  105. self.conf['port'] = cp.getint('db', 'port')
  106. self.conf['user'] = cp.get('db', 'user')
  107. self.conf['password'] = cp.get('db', 'password')
  108. self.conf['db'] = cp.get('db', 'db')
  109. self.conf['charset'] = 'utf8mb4' #默认编码UTF-8
  110. self.conf['cursorclass'] = pymysql.cursors.DictCursor #默认游标
  111.  
  112. def getConnect(self):
  113. if len(self.conn_list) == 0:
  114. raise Exception('连接池中目前没有可用的连接,请稍后再试')
  115. else:
  116. return self.conn_list.pop(0)#从连接池中取出最前面的一个连接实例
  117. def deleteAll(self):
  118. '''在程序运行时关闭连接池'''
  119. print('正在注销连接池')
  120. for conn in self.conn_list:#在删除连接池的时候调用析构函数并调用连接实例的析构函数来关闭所有连接
  121. conn.__del__()
  122. self.__del__()
  123. print('连接池注销完成')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement