1.数据库连接池思想处理mysql连接,完成数据库连接的业务逻辑
功能:有连接池管理的连接创建功能
执行sql语句功能,该功能应该适配工具类的增删改查所有需求
1 import time 2 from threading import Lock 3 class Connection: 4 def create_conn(self): #创建连接的方法生成连接 5 return (pymysql.connect(host='127.0.0.1',port=3306,user='root', 6 password='root',charset='utf8',db='sb',autocommit=True) 7 8 def __init__(self,max_count=5,timeout=0.5):#设置最大连接数为5,延迟时间为0.5秒 9 self.max_count = max_count 10 self.timeout = timeout 11 self.pool = []#创建连接池 12 self.current_count = 2 13 self.l = Lock() #加锁处理,解决变量安全 14 for i in range(self.current_count): #生成默认个数连接池 15 conn = self.create_conn 16 self.pool.append(conn) 17 def execute(self,sql,args=None,is_select=False):#执行sql语句函数,sql为要执行的字符串语句,args为sql语句的参数,is_select判断是否为查询语句,查询语句需要返回查询结果,其他只需要返回被影响的行数 18 while True: 19 if not self.pool: 20 l.acquire() 21 if self.current_count < self.max_count: 22 conn = self.create_conn() 23 self.pool.append(conn) 24 else: 25 time.sleep(0.2) 26 l.release() 27 else: 28 break 29 conn = self.pool.pop() 30 cursor = conn.cursor(pymsql.cursors.DictCursor) 31 affect_row = cursor.execute(sql,args) 32 if is_select: 33 fetch_all = cursor.fetchall() 34 self.pool.append(conn) 35 return fetch_all 36 self.pool.append(conn) 37 return affect_row
2.数据库工具类
1 from pool import Connection 2 class Mysql: 3 __conn = Connection() 4 @classmethod 5 def save(cls): 6 sql="" 7 args = [] 8 res = cls.__conn.execute(sql,args) 9 @classmethod 10 def delete(cls): 11 sql = "" 12 args = [] 13 res = cls.__conn.execute(sql,args) 14 @classmethod 15 def update(cls): 16 sql = "" 17 args = [] 18 cls.__conn.execute(sql) 19 @classmethod 20 def select(cls,id): 21 sql = "select * from user where id = %s" 22 args = [id] 23 res = cls.__conn.execute(sql,args,is_select=True) 24 print(res) 25 def task(): 26 Mysql.select(1) 27 from threading import Thread 28 Thread(target = task).start() 29 Thread(target = task).start() 30 Thread(target = task).start() 31 Thread(target = task).start() 32 Thread(target = task).start() 33 Thread(target = task).start()
3.封装好的orm框架
orm 关系 对象 映射 框架
首先要解决的问题 模型类 和 数据库表 的对应关系
1 import re #导入re模块 2 class CountError(Exeception): #自定义异常类 3 def __init__(self,msg): 4 self.msg = msg 5 class Field: #创建field类,属性分别为表的字段,name,约束条件,是否为主键,及默认值 6 def __init__(self,name,column_type,primary_key,default): 7 self.name = name 8 self.column_type = column_type 9 self.primary_key = primary_key 10 self.default = default 11 class StringField(Field): 12 def __init__(self,name,column_type='varchar(200)',primary_key=False,default=None): 13 super().__init__(name,column_type,primary_key,default) 14 class IntegerField(Field): 15 def __init__(self,name,column_type='int',primary_key=False,default=None): 16 super().__init__(name,column_type,primary_key,default) 17 class ModelMeta(type): 18 def __init__(cls,cls_name,bases,namespace): 19 if cls_name == "Models": 20 return type.__init__(cls,cls_name,bases,namespace) 21 table _name = cls_name.lower() #表名为类名的小写,需要将类名与表名统一 22 tags = [] #存放字段及约束条件的列表,tag = '字段1 类型 约束' 23 for k,v in namespace.items(): 24 tag = "" 25 if isinstance(v,Field): 26 tag += v.name + " " + v.column_type 27 if v.default is not None: 28 if isinstance(v.default.int): 29 tag += " default '%s'" %(v.default) 30 elif isinstance(v.default,int): 31 tag += " default %s" %v.default 32 else: 33 raise TypeError("不支持该默认类型") 34 tags.append(tag) 35 tag_str = ','.join(tags) 36 sql = "create table %s(%s)" %(table_name,tag_str) 37 if len(re.findall('primary',sql) != 1: 38 raise CountError("主键个数错误!") 39 print(sql) 40 return type.__init__(cls,cls_name,bases,namespace) 41 class Models(metaclass = ModelMeta): 42 pass
4.拓展
1 from orm import Models,IntegerField,StringField 2 class User(Models): 3 id = IntegerField('id',primary_key=True) 4 usr = StringField('usr','char(20)') 5 pwd = StringField('pwd','char(20)') 6 usr_type = IntegerField('usr_type',default=0) 7 pass 8 class Movie(Models): 9 id = IntegerField('id',primary_key=True) 10 name = StringField('name','char(20)') 11 path = StringField('path','varchar(100)')