orm功能封装
2024-09-03 12:31:25
封装功能:
查 : select
**kwargs.keys() --返回-> obj -转为-->list
[{},{}] ---> [obj,obj]
class Models(dict,metaclass=OSError):
def __getattr__(self, item):
#调用没有属性时触发
return self.get(item)
def __setattr__(self, key, value):
self[key] = value
@classmethod
def orm_select(cls,**kwargs):
mysql = MySQLClient()
if not kwargs:
sql = 'select * from %s' %cls.table_name
res = mysql.my_select(sql)
else:
key = list(kwargs.keys())[0]
value = kwargs.get(key)
sql = 'select * from %s where %s=? '%(
cls.table_name,key
)
sql = sql.replace('?','%s')
res = mysql.my_select(sql,value)
return [cls(**d) for d in res]
增:
def orm_insert(self):
mysql = SQLClient()
keys = []
values = []
args = []
for k , v in self.mappings.items():
if not v.primary_key:
keys.append(v.name)
values.append(
getattr(self,v.name,v.default)
)
args.append('?')
sql = 'insert into %s(%s) values(%s)' %(
self.table_name,
','.join(keys),
','.join(args)
)
sql = sql.replace('?','%s')
mysql.my_execute(sql,values)
改:
#更新
class Models(dict,metaclass=OSError):
def orm_update(self):
mysql = SQLClient()
keys = []
values = []
primary_key = None
for k,v in self.mappings.items():
if v.primary_key:
primary_key = v.name + '= %s' % getattr(self,v.name)
else:
keys.append(v.name + '=?')
values.append(
getattr(self,v.name)
)
sql = 'update %s set %s where %s' %(
self.table_name,
','.join(keys),
primary_key
)
sql = sql.replace('?','%s')
mysql.my_execute(sql,values)
连接数据库:
连接数据库
import pymysql
class MySQLClient:
def __init__(self):
self.client = pymysql.connect(
host ='localhost',
port = 3306,
user= 'root',
password = '123',
database = 'orm_demo',
charset = 'utf-8',
auto_increment = True
)
self.cursor = self.client.cursor(
pymysql.cursors.DictCursor
)
def my_select(self,sql,value=None):
self.cursor.execute(sql,value)
res = self.cursor.fetchall()
return res
def my_execute(self, sql, values):
try:
self.cursor.execute(sql, values)
except Exception as e:
print(e)
def close(self):
self.cursor.close()
self.client.close()
操作系统 : C
手机应用: iphone swift / objective-c
android java
3D : C / C ++
get / post :
仅请求资源
- 附带用户数据
最新文章
- 关系型数据库与NoSQL数据库
- C# 重载运算符
- linux上课
- IOS网络第二天 - 03-JSON显示数据,调用本地视频播放,数据转模型
- DirectBuffer
- SQL——用户定义函数
- floyd离散,最小环
- IPAdr.exe注册机[PY]
- windows下安装python,安装框架django。
- iOS开发——实战总结OC篇&;网易彩票开发知识点总结
- MSSQL生成整个数据库的SQL脚本的工具 scptxfr.exe
- R.Net 用法
- extjs combobox 设置下拉时显示滚动条 设置显示条数
- flex 载入GIF图片
- iOS实践04
- 转移服务器,DEDE网站遇到no input file specified!
- C# 调用C++ DLL 的类型转换
- WPF 自定义DataGrid控件样式
- UNIX网络编程——带外数据
- dede网站安全要做的四件事
热门文章
- WPF USB设备采集开源工具介绍
- HTML 引用大全
- C#读写设置修改调整UVC摄像头画面-曝光
- 创建你自己定制的vuejs plugin扩展app的功能
- python爬虫---CrawlSpider实现的全站数据的爬取,分布式,增量式,所有的反爬机制
- $parsers &; $formatters
- Web消息推送框架windows部署实践
- adb shell get/setprop, setenforce...
- jsp 获取后端配置文件.properties的某个配置内容
- xshell免费版