python: generator IDAL and DAL using sql server 2019
其他数据库一样的思维方式
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 TableModelBll class 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" pass def __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}Info class I{li.TableName}(ABC): \""" {li.TableDescription} \""" """ sb.append(sbt) tbll = TableModelBll() sinhead = f""" @classmethod def __subclasshook__(cls, subclass): return (hasattr(subclass, 'load_data_source') and callable(subclass.load_data_source) and hasattr(subclass, 'extract_text') and callable(subclass.extract_text) or NotImplemented) @abstractmethod def selectSql(cls) -> list: \""" :return: \""" pass @abstractmethod def selectSqlCount(cls) -> list: \""" 查询数据 总数 :return: \""" pass @abstractmethod def selectSqlOrder(cls, order: str) -> list: \""" :param order: :return: \""" pass @abstractmethod def selectSort(cls,field:str,isOrder:bool)->list: \""" :param field :param order: desc/asc :return: \""" pass @abstractmethod def selectIdSql(cls, {StrHelper.firstLower(li.FieldName)}: str): \""" :param {li.FieldName}: :return: \""" pass @abstractmethod def selectProc(cls): \""" :return: \""" pass @abstractmethod def selectIdProc(cls, {StrHelper.firstLower(li.FieldName)}): \""" :param {li.FieldName}: :return: \""" pass @abstractmethod def addSql(cls, info: {li.TableName}Info): \""" :param info: :return: \""" pass @abstractmethod def addProc(cls, info: {li.TableName}Info): \""" :param info: :return: \""" pass @abstractmethod def addOutProc(cls, info: {li.TableName}Info): \""" :param info: :return: \""" pass @abstractmethod def editSql(cls, info: {li.TableName}Info): \""" :param info: :return: \""" pass @abstractmethod def editProc(cls, info: {li.TableName}Info): \""" :param info: :return: \""" pass @abstractmethod def delSql(cls, {StrHelper.firstLower(li.FieldName)}): \""" :param {li.FieldName}: :return: \""" pass @abstractmethod def 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 TableModelBll class 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" pass def __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 row def 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 row def 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 row def 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 row def selectProc(cls)->list: \""" 存储过程 :return: \""" args = () row = cls.myms.executeCallProc("procSelect{li.TableName}All",args) return row def selectIdProc(cls,{li.FieldName}:str)->list: \""" 存储过程 :param {li.FieldName}: 主键ID :return: \""" args = ({li.FieldName},) row = cls.myms.executeCallProc('procSelect{li.TableName}', args) return row def 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 = 0 try: 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 = result except Exception as ex: print(ex) return id def 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 SchoolInfo class ISchool(ABC): """ 学校表 """ @classmethod def __subclasshook__(cls, subclass): return (hasattr(subclass, 'load_data_source') and callable(subclass.load_data_source) and hasattr(subclass, 'extract_text') and callable(subclass.extract_text) or NotImplemented) @abstractmethod def selectSql(cls) -> list: """ :return: """ pass @abstractmethod def selectSqlCount(cls) -> list: """ 查询数据 总数 :return: """ pass @abstractmethod def selectSqlOrder(cls, order: str) -> list: """ :param order: :return: """ pass @abstractmethod def selectSort(cls,field:str,isOrder:bool)->list: """ :param field :param order: desc/asc :return: """ pass @abstractmethod def selectIdSql(cls, schoolId: str): """ :param SchoolId: :return: """ pass @abstractmethod def selectProc(cls): """ :return: """ pass @abstractmethod def selectIdProc(cls, schoolId): """ :param SchoolId: :return: """ pass @abstractmethod def addSql(cls, info: SchoolInfo): """ :param info: :return: """ pass @abstractmethod def addProc(cls, info: SchoolInfo): """ :param info: :return: """ pass @abstractmethod def addOutProc(cls, info: SchoolInfo): """ :param info: :return: """ pass @abstractmethod def editSql(cls, info: SchoolInfo): """ :param info: :return: """ pass @abstractmethod def editProc(cls, info: SchoolInfo): """ :param info: :return: """ pass @abstractmethod def delSql(cls, schoolId): """ :param SchoolId: :return: """ pass @abstractmethod def 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 ISchool class 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 row def 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 row def 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 row def selectIdSql(cls,SchoolId:str)->list: """ :param SchoolId: 主键ID :return: """ row=cls.myms.execute(f"select * from School where SchoolId='{SchoolId}';") #考虑数据类型 #cls.myms.close() return row def selectProc(cls)->list: """ 存储过程 :return: """ args = () row = cls.myms.executeCallProc("procSelectSchoolAll",args) return row def selectIdProc(cls,SchoolId:str)->list: """ 存储过程 :param SchoolId: 主键ID :return: """ args = (SchoolId,) row = cls.myms.executeCallProc('procSelectSchool', args) return row def 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 = 0 try: outid =('int',) #输出,元组类型 print(info) args = [info.SchoolName,info.SchoolTelNo,outSchoolId] print(args) result=cls.myms.insertOutCallProc("procInsertSchoolOutput", args) print(result) id = result except Exception as ex: print(ex) return id def 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 =SchoolId k=cls.myms.deleteProc("procDuDeleteSchool", args) return k
拼就是一个粗放的项目
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)