orm_pool:
import pymysql,time
from threading import Lock
l=Lock()
class Connection: #创建连接类,处理与数据库之间的连接,初始化默认最大连接数为5,
def create_conn(self): #产生连接
return pymysql.connect(
host = '127.0.0.1',
port = 3306,user = 'root',password = 'root',db = 'sb',charset = 'utf8',autocommit = True)
def __init__(self,max_count=5,timeout =0.5): #生成对象,产生两个连接,
self.max_count = max_count
self.timeout = timeout
self.pool=[]
self.current_count =2
for i in range(self.current_count):
conn = self.create_conn()
self.pool.append(conn)
def execute(self,sql,args=None,is_select=False):#执行sql语句,先判断连接池中是否有空闲连接,返回执行sql语句的结果,需要传入sql语句
while True:
if not self.pool:
l.acquire()
if self.current_count < self.max_count:
conn = self.create_conn()
self.pool.append(conn)
self.current_count+=1
else:
time.sleep(self.timeout)
l.release()
else:
break
conn = self.pool.pop()
cursor = conn.cursor(pymysql.cursors.DictCursor)
affect_row = 0
try:
affect_row = cursor.execute(sql,args) 当sql语句出错时,捕捉异常
except pymysql.err.InternalError as e:
print(e)
if is_select: #当是查询时,需要返回查询的结果
fetch_all = cursor.fetchall()
self.pool.append(conn)
return fetch_all
self.pool.append(conn)
return affect_row #其他事只需要返回结果,当有行数被影响时,返回正整数,没有时为0
orm.tool:
from .orm_pool import Connection
class Mysql: #创建数据库连接,实现增删改查功能
__conn = Connection(max_count=5)
@classmethod
def create(cls,sql):
return cls.__conn.extcute(sql)
@classmethod
def get_name(cls,obj):
return obj.__class__.__name__.lower()
@classmethod
def save(cls,obj):
table_name = cls.get_name(obj)
col_str = ""
val_str = ""
args = []
for k,v in obj.__dict__.items():
col_str += k+","
val_str +="%s,"
args.append(v)
col_str = col_str[0:-1]
val_str = val_str[0:-1]
sql = "insert into %s(%s) values(%s)"%(table_name,col_str,val_str)
return cls__conn.execute(sql,args)
@classmethod
def delete(cls,obj):
table_name = cls.get_name(obj)
sql = "delete from %s where id=%s"
args = [table_name,obj.id]
return cls.__conn.execute(sql,args)
@classmethod
def update(cls,obj):
table_name = cls.get_name(obj)
tags =[]
args = []
for k,v in obj.__dict__.items():
tag ="" + k+"=%s"
tags.append(tag)
args.append(v)
tag_str = ','.join(tags)
sql = "update %s set %s where id=%s"%(table_name,tag_str,obj.id)
return cls.__conn.execute(sql,args)
@classmethod
def select_by_id(cls,class_name,id):
table_name = class_name.__name__.lower()
sql = "select * from %s where id =%s"%(table_name,id)
res = cls.__conn.execute(sql,is_select=True)
if not res:
return None
obj_dic = res[0]
obj = object.__new(class_name)
obj.__dict__ = obj.dict
return obj
@classmethod
def select_many(cls,class_name,conditions=None):
table_name = class_name.__name__.lower()
sql = "select * from %s "%(table_name)
if conditions:
sql += " " + conditions
res = cls.__conn.execute(sql,is_select=True)
if not res:
retuen None
objs =[]
for dic in res:
obj = object.__new__(class_name)
obj.__dict__ = dic
objs.append(obj)
return objs
orm:
import re
class CountError(Exception):
def __init__(self,msg):
self.msg = msg
class Field:
def __init__(self,name,column_type,primary_key,default):
self.name = name
self.column_type = column_type
self.primary_key = primary_key
self.default = default
class StringField(Field):
def __init__(self,name,column_type='varchar(200)',primary_key=False,default=None)
super().__init__(name,column_type,primary_key,default)
class IntegerField(Field):
def __init__(self,name,column_type='int',primaery_key = False,default=None):
super().__init__(name,column_type,primary_key,default)
class ModelMeta(type):
def __init__(cls,cls_name,bases,namespace):
if cla_name == "Models::
return type.__init__(cls,cls_name,bases,namespace)
table_name cls_name.lower()
tags=[]
for k,v in namespace.items():
tag=""
if instance(v,Field):
tag+=v.name+" "+v.column_type
if v.primary_key:
tag+=" primary key auto_increment"
if v.default is not None:
if isinstance(v.default,str):
tag +="default '%s'"%(v.default)
elif isinstance(v.default,int):
tag+=" default %s"%(v.default)
else:
raise TypeError("该类型不支持")
tags.append(tag)
tag_str = ','.join(tags)
sql = "create table %s(%s)"%(table_name,tag_str)
if len(re,findall('primary',sql) !=1:
raise CountError("主键个数错误!")
print(sql)
from .orm_tool import Mysql
Mysql.create(sql)
return type.__init__(cls,cls_name,bases,namespace)
class Models(metaclass = ModelMeta):
def __str__(self):
return self.__class__.__name__+":"+str(self.__dict__)