其它数据库也是一样的思维方式
create IDAL
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# OS : windows 10
# Datetime : 2024/11/18 21:10
# User : geovindu
# Product : PyCharm
# Project : pyGenerator
# File : SqlServerGenerator/createInterface.py
# explain : 学习
import os
import re
import sys
import io
import datetime
from common.fileHelper import FileHelper
from common.strHelper import StrHelper
from bll.tableNameAndKey import TableNameAndKeyBll
from bll.tableForegin import TableForeginBll
from bll.tableModel import TableModelBllclass CreateInterface(object):""""""def __init__(self):self.__modelpath = os.path.join(os.getcwd() + "/test/interface/")self.__file = FileHelper()self.__blltablekey = TableNameAndKeyBll()self.__database = "sql server 2019"self.__name = "CreateInterface"passdef __del__(self):""":return:"""print(f"{self.__name} ERASE MEMORY")def addpackagefile(self):"""生成包配置文件:return:"""now = datetime.datetime.now()bll = TableNameAndKeyBll()sb = []sbt = f"""
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# OS : windows 10
# Datetime : {now.strftime('%Y-%m-%d %H:%M:%S')}
# database :{self.__database}
# User : geovindu
# Product : PyCharm
# Project : IctGame
# File : interface/__init__.py
# explain : 学习"""sb.append(sbt)for li in bll.selectSql():sbp=f"""
from interface.{StrHelper.firstLower(li.TableName)} import I{li.TableName}
"""sb.append(sbp)if not os.path.exists(self.__modelpath):os.makedirs(self.__modelpath)filepath = self.__modelpath + '__init__.py'content = ''.join(sb)ok = self.__file.createModelFile(filepath, content)def add(self):"""生成实体:return:"""# fileHelper=FileHelper()now = datetime.datetime.now()bll = TableNameAndKeyBll()for li in bll.selectSql():sb = []sbt = f"""
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# OS : windows 10
# Datetime : {now.strftime('%Y-%m-%d %H:%M:%S')}
# database :{self.__database}
# User : geovindu
# Product : PyCharm
# Project : IctGame
# File : interface/{li.TableName}.py
# explain : 学习
from __future__ import annotations
from abc import ABC, abstractmethod
import os
import sys
from model.{StrHelper.firstLower(li.TableName)} import {li.TableName}Infoclass I{li.TableName}(ABC):\"""{li.TableDescription} \"""
"""sb.append(sbt)tbll = TableModelBll()sinhead = f"""@classmethoddef __subclasshook__(cls, subclass):return (hasattr(subclass, 'load_data_source') andcallable(subclass.load_data_source) andhasattr(subclass, 'extract_text') andcallable(subclass.extract_text) orNotImplemented) @abstractmethoddef selectSql(cls) -> list:\""":return:\"""pass@abstractmethoddef selectSqlCount(cls) -> list:\"""查询数据 总数:return:\"""pass@abstractmethoddef selectSqlOrder(cls, order: str) -> list:\""":param order::return:\"""pass@abstractmethoddef selectSort(cls,field:str,isOrder:bool)->list:\""":param field:param order: desc/asc:return:\"""pass@abstractmethoddef selectIdSql(cls, {StrHelper.firstLower(li.FieldName)}: str):\""":param {li.FieldName}::return:\"""pass@abstractmethoddef selectProc(cls):\""":return:\"""pass@abstractmethoddef selectIdProc(cls, {StrHelper.firstLower(li.FieldName)}):\""":param {li.FieldName}::return:\"""pass@abstractmethoddef addSql(cls, info: {li.TableName}Info):\""":param info::return:\"""pass@abstractmethoddef addProc(cls, info: {li.TableName}Info):\""":param info::return:\"""pass@abstractmethoddef addOutProc(cls, info: {li.TableName}Info):\""":param info::return:\"""pass@abstractmethoddef editSql(cls, info: {li.TableName}Info):\""":param info::return:\"""pass@abstractmethoddef editProc(cls, info: {li.TableName}Info):\""":param info::return:\"""pass@abstractmethoddef delSql(cls, {StrHelper.firstLower(li.FieldName)}):\""":param {li.FieldName}::return:\"""pass@abstractmethoddef delProc(cls, {StrHelper.firstLower(li.FieldName)}):\""":param {li.FieldName}::return:\"""pass """sb.append(sinhead)if not os.path.exists(self.__modelpath):os.makedirs(self.__modelpath)filepath = self.__modelpath + StrHelper.firstLower(li.TableName) + '.py'content = ''.join(sb)ok = self.__file.createModelFile(filepath, content)
create DAL
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# OS : windows 10
# Datetime : 2024/11/18 21:10
# User : geovindu
# Product : PyCharm
# Project : pyGenerator
# File : SqlServerGenerator/createDal.py
# explain : 学习
import os
import re
import sys
import io
import datetime
from common.fileHelper import FileHelper
from common.strHelper import StrHelper
from bll.tableNameAndKey import TableNameAndKeyBll
from bll.tableForegin import TableForeginBll
from bll.tableModel import TableModelBllclass CreateDal(object):""""""def __init__(self):self.__modelpath = os.path.join(os.getcwd() + "/test/dal/")self.__file = FileHelper()self.__blltablekey = TableNameAndKeyBll()self.__bllTableModel = TableModelBll()self.__database = "sql server 2019"self.__name = "CreateDal"passdef __del__(self):""":return:"""print(f"{self.__name} ERASE MEMORY")def getColumn(self,tableName:str) -> str:"""column=("SchoolId","SchoolName","SchoolTelNo"):return:"""tables = self.__bllTableModel.selectSql(tableName)columns = []columnstr = '('if len(tables) > 0:for obj in tables:columns.append("\""+obj.FieldName+"\"")columnstr =columnstr + ','.join(columns)return columnstr+')'def getVales(self,tableName:str) -> str:"""egs:vales=[info.SchoolId,info.SchoolName,info.SchoolTelNo]:return:"""vales = []valesstr = '['tables = self.__bllTableModel.selectSql(tableName)if len(tables)>0:for obj in tables:vales.append('info.'+obj.FieldName)valesstr = valesstr+','.join(vales)return valesstr + ']'def getArgs(self,tableName:str) -> str:"""egs:args = [info.SchoolId,info.SchoolName,info.SchoolTelNo] #修改的args ={{"schoolId":f"{{info.schoolId}}","SchoolName":f"{{info.SchoolName}}","SchoolTelNo":f"{{info.SchoolTelNo}}"}}:return:"""args = []argsstr = '['tables = self.__bllTableModel.selectSql(tableName)if len(tables)>0:for obj in tables:args.append('info.'+obj.FieldName)argsstr =argsstr+ ','.join(args)return argsstr+']'def getArgs(self,tableName:str) -> str:"""egs:args = [info.SchoolId,info.SchoolName,info.SchoolTelNo] #修改的:return:"""args = []argsstr = '['tables = self.__bllTableModel.selectSql(tableName)if len(tables)>0:for obj in tables:args.append('info.'+obj.FieldName)argsstr = argsstr+','.join(args)return argsstr+']'def getArgsVariable(self,tableName:str) -> str:"""egs:args ={"schoolId":f"{{info.schoolId}}","SchoolName":f"{{info.SchoolName}}","SchoolTelNo":f"{{info.SchoolTelNo}}"}}:return:"""args = []argsstr = '{'tables = self.__bllTableModel.selectSql(tableName)if len(tables)>0:for obj in tables:args.append("\""+obj.FieldName+"\":f\"{info."+obj.FieldName+"}\"")argsstr =argsstr+ ','.join(args)return argsstr+'}'def getArgsOut(self,tableName:str, primekey:str) -> str:"""egs:args = [info.SchoolName, info.SchoolTelNo,outid] #添加返回值:return:"""args = []argsstr = '['tables = self.__bllTableModel.selectSql(tableName)if len(tables)>0:for obj in tables:if str(obj.FieldName).lower() != primekey.lower():args.append('info.'+obj.FieldName)argsstr = argsstr+','.join(args)return argsstr+',out'+primekey+']'def addpackagefile(self):"""生成包配置文件:return:"""now = datetime.datetime.now()bll = TableNameAndKeyBll()sb = []sbt = f"""
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# OS : windows 10
# Datetime : {now.strftime('%Y-%m-%d %H:%M:%S')}
# database :{self.__database}
# User : geovindu
# Product : PyCharm
# Project : IctGame
# File : dal/__init__.py
# explain : 学习"""sb.append(sbt)for li in bll.selectSql():sbp=f"""
from dal.{StrHelper.firstLower(li.TableName)} import {li.TableName}Dal
"""sb.append(sbp)if not os.path.exists(self.__modelpath):os.makedirs(self.__modelpath)filepath = self.__modelpath + '__init__.py'content = ''.join(sb)ok = self.__file.createModelFile(filepath, content)def add(self):"""生成实体:return:"""# fileHelper=FileHelper()now = datetime.datetime.now()bll = TableNameAndKeyBll()for li in bll.selectSql():sb = []sbt = f"""
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# OS : windows 10
# Datetime : {now.strftime('%Y-%m-%d %H:%M:%S')}
# database :{self.__database}
# User : geovindu
# Product : PyCharm
# Project : IctGame
# File : dal/{li.TableName}.py
# explain : 学习
from __future__ import annotations
from abc import ABC, abstractmethod
import os
import sys
from model.{StrHelper.firstLower(li.TableName)} import {li.TableName}Info
from DBUtility.MsSQLHelper import MsSqlHelper
from interface.{StrHelper.firstLower(li.TableName)} import I{li.TableName}class {li.TableName}Dal(I{li.TableName}):\"""{li.TableDescription} \"""
"""sb.append(sbt)sinhead = f"""myms = MsSqlHelper()def __init__(self):\"""构造函数,方法:param strserver::param struser::param strpwd::param strdatabase:\"""self._strserver = ""self._struser = ""self._strpwd = ""self._strdatabase =""def selectSql(cls)->list:\"""查询数据 self._strserver, self._struser, self._strpwd, self._strdatabase:return:\"""row=cls.myms.execute("select * from {li.TableName};")#cls.myms.close()return rowdef selectSqlCount(cls)->list:\"""查询数据 总数:return:\"""row=cls.myms.execute("select count(*) as total from {li.TableName};")#cls.myms.close()return row[0]def selectSqlOrder(cls,order:str)->list:\""":param order: SchoolId desc/asc:return:\"""students=[]strsql=f"select * from {li.TableName} order by {{order}};"row=cls.myms.execute(f"select * from {li.TableName} order by {{order}};")return rowdef selectSort(cls,field:str,isOrder:bool)->list:\""":param field {li.FieldName}:param order: desc/asc:return:\"""order='desc'if isOrder==True:order='desc'else:order='asc'strsql=f"select * from {li.TableName} order by {{field}} {{order}};"row=cls.myms.execute(f"select * from {li.TableName} order by {{field}} {{order}};")#cls.myms.close()return rowdef selectIdSql(cls,{li.FieldName}:str)->list:\""":param {li.FieldName}: 主键ID:return:\"""row=cls.myms.execute(f"select * from {li.TableName} where SchoolId='{{SchoolId}}';") #考虑数据类型#cls.myms.close()return rowdef selectProc(cls)->list:\"""存储过程:return:\"""args = ()row = cls.myms.executeCallProc("procSelect{li.TableName}All",args)return rowdef selectIdProc(cls,{li.FieldName}:str)->list:\"""存储过程:param {li.FieldName}: 主键ID:return:\"""args = ({li.FieldName},)row = cls.myms.executeCallProc('procSelect{li.TableName}', args)return rowdef addSql(cls,info:{li.TableName}Info)->int:\"""添加,要考虑添加返回ID值:param info:实体类:return:\"""column={self.getColumn(li.TableName)}vales={self.getVales(li.TableName)}return cls.myms.insertByColumnaAndValues("{li.TableName}",column,vales)def addProc(cls,info:{li.TableName}Info)->int:\"""添加,要考虑添加返回ID值:param info:实体类:return:\"""args={self.getArgs(li.TableName)}return cls.myms.insertCallProc("procInsert{li.TableName}",args)def addOutProc(cls,info:{li.TableName}Info) -> int:\"""添加,要考虑添加返回ID值:param info:实体类:return: 返回增加的ID\"""id = 0try:outid =('int',) #输出,元组类型print(info)args = {self.getArgsOut(li.TableName,li.FieldName)}print(args)result=cls.myms.insertOutCallProc("procInsert{li.TableName}Output", args)print(result)id = resultexcept Exception as ex:print(ex)return iddef editSql(cls,info:{li.TableName}Info)->int:\""":param info:实体类:return:\"""args = {self.getArgsVariable(li.TableName)}where = f"{li.FieldName}={{info.{li.FieldName}}}" ##print(args,where)return cls.myms.updateByKeyValues("{li.TableName}",where,args)def editProc(cls, info: {li.TableName}Info)->int:\""":param info: 实体类:return:\"""args = {self.getArgs(li.TableName)}return cls.myms.updateProc("procUpdate{li.TableName}",args)def delSql(cls,{li.FieldName}:str)->int:\"""sql语句删除:param {li.FieldName}: 主键ID:return:\"""where={{f"{li.FieldName}":{li.FieldName}}}return cls.myms.deleteByKeyValues("{li.TableName}",where)def delProc(cls, {li.FieldName}:str)->int:\"""删除 存储过程 删除多个ID,后面增加:param {li.FieldName}: 主键ID:return:\"""args ={li.FieldName}k=cls.myms.deleteProc("procDuDelete{li.TableName}", args)return k
"""sb.append(sinhead)if not os.path.exists(self.__modelpath):os.makedirs(self.__modelpath)filepath = self.__modelpath + StrHelper.firstLower(li.TableName) + '.py'content = ''.join(sb)ok = self.__file.createModelFile(filepath, content)
生成的代码:
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# OS : windows 10
# Datetime : 2024-11-19 21:12:32
# database :sql server 2019
# User : geovindu
# Product : PyCharm
# Project : IctGame
# File : interface/School.py
# explain : 学习
from __future__ import annotations
from abc import ABC, abstractmethod
import os
import sys
from model.school import SchoolInfoclass ISchool(ABC):"""学校表 """@classmethoddef __subclasshook__(cls, subclass):return (hasattr(subclass, 'load_data_source') andcallable(subclass.load_data_source) andhasattr(subclass, 'extract_text') andcallable(subclass.extract_text) orNotImplemented) @abstractmethoddef selectSql(cls) -> list:""":return:"""pass@abstractmethoddef selectSqlCount(cls) -> list:"""查询数据 总数:return:"""pass@abstractmethoddef selectSqlOrder(cls, order: str) -> list:""":param order::return:"""pass@abstractmethoddef selectSort(cls,field:str,isOrder:bool)->list:""":param field:param order: desc/asc:return:"""pass@abstractmethoddef selectIdSql(cls, schoolId: str):""":param SchoolId::return:"""pass@abstractmethoddef selectProc(cls):""":return:"""pass@abstractmethoddef selectIdProc(cls, schoolId):""":param SchoolId::return:"""pass@abstractmethoddef addSql(cls, info: SchoolInfo):""":param info::return:"""pass@abstractmethoddef addProc(cls, info: SchoolInfo):""":param info::return:"""pass@abstractmethoddef addOutProc(cls, info: SchoolInfo):""":param info::return:"""pass@abstractmethoddef editSql(cls, info: SchoolInfo):""":param info::return:"""pass@abstractmethoddef editProc(cls, info: SchoolInfo):""":param info::return:"""pass@abstractmethoddef delSql(cls, schoolId):""":param SchoolId::return:"""pass@abstractmethoddef delProc(cls, schoolId):""":param SchoolId::return:"""pass
# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author : geovindu,Geovin Du 涂聚文.
# IDE : PyCharm 2023.1 python 3.11
# OS : windows 10
# Datetime : 2024-11-19 21:12:32
# database :sql server 2019
# User : geovindu
# Product : PyCharm
# Project : IctGame
# File : dal/School.py
# explain : 学习
from __future__ import annotations
from abc import ABC, abstractmethod
import os
import sys
from model.school import SchoolInfo
from DBUtility.MsSQLHelper import MsSqlHelper
from interface.school import ISchoolclass SchoolDal(ISchool):"""学校表 """myms = MsSqlHelper()def __init__(self):"""构造函数,方法:param strserver::param struser::param strpwd::param strdatabase:"""self._strserver = ""self._struser = ""self._strpwd = ""self._strdatabase =""def selectSql(cls)->list:"""查询数据 self._strserver, self._struser, self._strpwd, self._strdatabase:return:"""row=cls.myms.execute("select * from School;")#cls.myms.close()return rowdef selectSqlCount(cls)->list:"""查询数据 总数:return:"""row=cls.myms.execute("select count(*) as total from School;")#cls.myms.close()return row[0]def selectSqlOrder(cls,order:str)->list:""":param order: SchoolId desc/asc:return:"""students=[]strsql=f"select * from School order by {order};"row=cls.myms.execute(f"select * from School order by {order};")return rowdef selectSort(cls,field:str,isOrder:bool)->list:""":param field SchoolId:param order: desc/asc:return:"""order='desc'if isOrder==True:order='desc'else:order='asc'strsql=f"select * from School order by {field} {order};"row=cls.myms.execute(f"select * from School order by {field} {order};")#cls.myms.close()return rowdef selectIdSql(cls,SchoolId:str)->list:""":param SchoolId: 主键ID:return:"""row=cls.myms.execute(f"select * from School where SchoolId='{SchoolId}';") #考虑数据类型#cls.myms.close()return rowdef selectProc(cls)->list:"""存储过程:return:"""args = ()row = cls.myms.executeCallProc("procSelectSchoolAll",args)return rowdef selectIdProc(cls,SchoolId:str)->list:"""存储过程:param SchoolId: 主键ID:return:"""args = (SchoolId,)row = cls.myms.executeCallProc('procSelectSchool', args)return rowdef addSql(cls,info:SchoolInfo)->int:"""添加,要考虑添加返回ID值:param info:实体类:return:"""column=("SchoolId","SchoolName","SchoolTelNo")vales=[info.SchoolId,info.SchoolName,info.SchoolTelNo]return cls.myms.insertByColumnaAndValues("School",column,vales)def addProc(cls,info:SchoolInfo)->int:"""添加,要考虑添加返回ID值:param info:实体类:return:"""args=[info.SchoolId,info.SchoolName,info.SchoolTelNo]return cls.myms.insertCallProc("procInsertSchool",args)def addOutProc(cls,info:SchoolInfo) -> int:"""添加,要考虑添加返回ID值:param info:实体类:return: 返回增加的ID"""id = 0try:outid =('int',) #输出,元组类型print(info)args = [info.SchoolName,info.SchoolTelNo,outSchoolId]print(args)result=cls.myms.insertOutCallProc("procInsertSchoolOutput", args)print(result)id = resultexcept Exception as ex:print(ex)return iddef editSql(cls,info:SchoolInfo)->int:""":param info:实体类:return:"""args = {"SchoolId":f"{info.SchoolId}","SchoolName":f"{info.SchoolName}","SchoolTelNo":f"{info.SchoolTelNo}"}where = f"SchoolId={info.SchoolId}" ##print(args,where)return cls.myms.updateByKeyValues("School",where,args)def editProc(cls, info: SchoolInfo)->int:""":param info: 实体类:return:"""args = [info.SchoolId,info.SchoolName,info.SchoolTelNo]return cls.myms.updateProc("procUpdateSchool",args)def delSql(cls,SchoolId:str)->int:"""sql语句删除:param SchoolId: 主键ID:return:"""where={f"SchoolId":SchoolId}return cls.myms.deleteByKeyValues("School",where)def delProc(cls, SchoolId:str)->int:"""删除 存储过程 删除多个ID,后面增加:param SchoolId: 主键ID:return:"""args =SchoolIdk=cls.myms.deleteProc("procDuDeleteSchool", args)return k
拼就是一个粗放的项目