首页 > 数据库 >python: more Layer Architecture and its Implementation in Python and sql server

python: more Layer Architecture and its Implementation in Python and sql server

时间:2024-11-06 22:30:53浏览次数:3  
标签:info Layer SchoolId return Python self python def cls

sql server:

create table School  -- 創建表
(
   SchoolId char(5) NOT NULL PRIMARY KEY,    
    SchoolName nvarchar(500) NOT NULL DEFAULT '', 
    SchoolTelNo  varchar(8)  NULL DEFAULT '' , 
  
); 
go

  

model:

# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功的功臣,還需要行爲每日來值班嗎?
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# Datetime  : 2024/10/12 22:53
# User      : geovindu
# Product   : PyCharm
# Project   : IctGame
# File      : model/school.py
# explain   : 学习

class SchoolInfo(object):
    """
    學校實體對象
    https://docs.python.org/3/library/functions.html
    https://docs.python.org/3/howto/descriptor.html
    """

    def __init__(self):
        """
        構造
        """
        self._SchoolId = None
        """
        primary key
        """
        self._SchoolName = None
        """
        學校名稱
        """
        self._SchoolTelNo = None
        """
        學校電號碼
        """

    @property
    def SchoolId(self):
        """
        primary key
        """
        return self._SchoolId

    @SchoolId.setter
    def SchoolId(self, schoolId):
        """
        primary key
        :param SchoolId:
        :return:
        """
        self._SchoolId = schoolId

    @property
    def SchoolName(self):
        """
        學校名稱
        """
        return self._SchoolName

    @SchoolName.setter
    def SchoolName(self, schoolName):
        """
        學校名稱
        :param SchoolName:
        :return:
        """
        self._SchoolName = schoolName

    @property
    def SchoolTelNo(self):
        """
        學校電話
        """
        return self._SchoolTelNo

    @SchoolTelNo.setter
    def SchoolTelNo(self, schoolTelNo):
        """
        學校電話 賦值
        :param SchoolTelNo:
        :return:
        """
        self._SchoolTelNo = schoolTelNo

    '''
    def ToString(self):
        """
        顯示一行實體對象
        :return:
        """
        return "{0}\t{1}\t{2}".format(self._SchoolId, self._SchoolName, self._SchoolTelNo)



    def __del__(self):
        print('{}对象已经被销毁'.format(self.__name__))

    '''
# test

  

IDAL:

# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功的功臣,還需要行爲每日來值班嗎?
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# Datetime  : 2024/10/31 20:40
# User      : geovindu
# Product   : PyCharm
# Project   : IctGame
# File      : 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):
        """

        :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 SchoolId
        :param order:  desc/asc
        :return:
        """
        pass

    @abstractmethod
    def selectIdSql(cls, SchoolId: str):
        """

        :param StudentId:
        :return:
        """
        pass

    @abstractmethod
    def selectProc(cls):
        """

        :return:
        """
        pass

    @abstractmethod
    def selectIdProc(cls, SchoolId: str):
        """

        :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: str):
        """

        :param SchoolId:
        :return:
        """
        pass

    @abstractmethod
    def delProc(cls, SchoolId:str):
        """

        :param SchoolId:
        :return:
        """
        pass

  

DAL:

# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功的功臣,還需要行爲每日來值班嗎?
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# Datetime  : 2024/10/31 20:40
# User      : geovindu
# Product   : PyCharm
# Project   : IctGame
# File      : school.py
# explain   : 学习

import os
import sys
from pathlib import Path
import re
import pymssql  #sql server
from model.school import SchoolInfo
from DBUtility.MsSQLHelper import MsSqlHelper
from sqlserverinterface.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 StudentId: 主键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,outid]
            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}"}  #"StudentId":6
        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

  

BLL:

# encoding: utf-8
# 版权所有 2024 ©涂聚文有限公司
# 许可信息查看:言語成了邀功的功臣,還需要行爲每日來值班嗎?
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 3.11
# OS        : windows 10
# Datetime  : 2024/10/31 20:40
# User      : geovindu
# Product   : PyCharm
# Project   : IctGame
# File      : school.py
# explain   : 学习

import os
import sys
from pathlib import Path
import re
import pymssql  #sql server
from datetime import date
from model.school import SchoolInfo
from field.school import SchoolField
from sqlserverfactory.AbstractFactory import AbstractFactory


class SchoolBll(object):
    """
    学生信息操作业务类
    """

    dal=AbstractFactory.createSchool
    """
    类属性 接口DAL
    """
    def __init__(self):
        """

        """
        self.__name = "SchoolBll"
        self._field = SchoolField()

    def __del__(self):
        print(f"{self.__name} ERASE MEMORY")


    def select(self) -> list[SchoolInfo]:
        """

        :return:
        """

        students = []

        data = self.dal().selectSql()
        if len(data) > 0:
            for SchoolId, SchoolName, SchoolTelNo in data[0]:
                info = SchoolInfo()
                info.SchoolId = SchoolId
                info.SchoolName = SchoolName
                info.SchoolTelNo = SchoolTelNo
                students.append(info)
        return students

    def selectSql(cls) -> list[SchoolInfo]:
        """
        元组数据
        :return: list 列表
        """
        students = []

        data = cls.dal().selectSql()
        if len(data) > 0:
            for SchoolId,SchoolName,SchoolTelNo in data[0]:
                info=SchoolInfo()
                info.SchoolId=SchoolId
                info.SchoolName=SchoolName
                info.SchoolTelNo=SchoolTelNo
                students.append(info)
        return students

    def show(self)-> int:
        """

        :return:
        """
        students = []
        k=-1
        data = self.dal().selectSql()
        if len(data) > 0:
            for SchoolId,SchoolName,SchoolTelNo in data[0]:
                info = SchoolInfo()
                info.SchoolId = SchoolId
                info.SchoolName = SchoolName
                info.SchoolTelNo = SchoolTelNo
                students.append(info)
                k=1

            print("┌{:<10s}┬{:<70s}┬{:<20s}┐".format("─" * 10, "─" * 70, "─" * 20))
            print(self._field.Title)
            print("├{:<10s}┼{:<70s}┼{:<20s}┤".format("═"*10, "═"*70, "═"*20))
            i=1
            for info in data:
                print("│{:<10s}│{:<70s}│{:<20s}│".format(info.SchoolId.center(10), " {}".format(info.SchoolName.strip()),
                                                         info.SchoolTelNo.center(20)))  # rjust  ljust
                if i<len(data):
                    print("├{:<10s}┼{:<70s}┼{:<20s}┤".format("─" * 10, "─" * 70, "─" * 20))
                i=i+1

            print("└{:<10s}┴{:<70s}┴{:<20s}┘".format("─" * 10, "─" * 70, "─" * 20))


        return k


    def selectSqlCount(cls) -> int:
        """
        查询数据 总数
        :return:
        """
        #print(cls.dal().selectSqlCount()[0][0])
        total=cls.dal().selectSqlCount()[0][0]
        return total

    def Count(self) -> int:
        """
        查询数据 总数
        :return:
        """
        total=self.dal().selectSqlCount()[0][0]
        return total

    def selectSqlOrder(cls, order: str) -> list[SchoolInfo]:
        """
        元组数据
        :param order: SchoolName desc/asc
        :return:
        """
        students=[]
        data = cls.dal().selectSqlOrder(order)
        if len(data) > 0:
            for SchoolId,SchoolName,SchoolTelNo in data[0]:
                info=SchoolInfo()
                info.SchoolId=SchoolId
                info.SchoolName=SchoolName
                info.SchoolTelNo=SchoolTelNo
                students.append(info)
        return students


    def selectSort(cls,field:str,isOrder:bool)->list[SchoolInfo]:
        """

        :param field SchoolId
        :param order:  desc/asc
        :return:
        """
        students=[]
        data = cls.dal().selectSort(field,isOrder)
        if len(data) > 0:
            for SchoolId, SchoolName, SchoolTelNo in data[0]:
                info = SchoolInfo()
                info.SchoolId = SchoolId
                info.SchoolName = SchoolName
                info.SchoolTelNo = SchoolTelNo
                students.append(info)
        return students

    def display(self,data:list[SchoolInfo]):
        """

        :param data:
        :return:
        """
        if len(data) > 0:
            print("┌{:<10s}┬{:<70s}┬{:<20s}┐".format("─" * 10, "─" * 70, "─" * 20))
            print(self._field.Title)
            print("├{:<10s}┼{:<70s}┼{:<20s}┤".format("═"*10, "═"*70, "═"*20))
            i=1
            for info in data:
                print("│{:<10s}│{:<70s}│{:<20s}│".format(info.SchoolId.center(10), " {}".format(info.SchoolName.strip()),
                                                         info.SchoolTelNo.center(20)))  # rjust  ljust
                if i<len(data):
                    print("├{:<10s}┼{:<70s}┼{:<20s}┤".format("─" * 10, "─" * 70, "─" * 20))
                i=i+1

            print("└{:<10s}┴{:<70s}┴{:<20s}┘".format("─" * 10, "─" * 70, "─" * 20))

    def selectIdSql(cls,SchoolId:str) -> list[SchoolInfo]:
        """

        :param SchoolId:ID
        :return:
        """
        students = []
        data = cls.dal().selectIdSql(SchoolId)
        #print(data)
        if len(data)>0:
            for SchoolId,SchoolName,SchoolTelNo in data[0]:
                info = SchoolInfo()
                info.SchoolId = SchoolId
                info.SchoolName = SchoolName
                info.SchoolTelNo = SchoolTelNo
                students.append(info)
        return students


    def selectProc(cls) -> list[SchoolInfo]:
        """

        :return:
        """
        students=[]
        data = cls.dal().selectProc()
        #print(data)
        if len(data) > 0:
            for SchoolId,SchoolName,SchoolTelNo in data:
                info = SchoolInfo()
                info.SchoolId = SchoolId
                info.SchoolName = SchoolName
                info.SchoolTelNo = SchoolTelNo
                students.append(info)
        return students

    def selectIdProc(cls,StudentId:str) -> list[SchoolInfo]:
        """

        :param StudentId:
        :return:
        """
        students = []
        data = cls.dal().selectIdProc(StudentId)
        if len(data) > 0:
            for SchoolId,SchoolName,SchoolTelNo in data:
                info = SchoolInfo()
                info.SchoolId = SchoolId
                info.SchoolName = SchoolName
                info.SchoolTelNo = SchoolTelNo
                students.append(info)
        return students

    def addSql(cls,info:SchoolInfo) -> int:
        """

        :param info:实体类
        :return:
        """
        return cls.dal().addSql(info)


    def add(self,info:SchoolInfo) -> int:
        """

        :param info:实体类
        :return:
        """
        return self.dal().addSql(info)


    def addProc(cls,info:SchoolInfo) -> int:
        """

        :param info:实体类
        :return:
        """
        #print(info)
        return cls.dal().addProc(info)

    def addOutProc(cls,info:SchoolInfo)->int:
        """

        :param info: 实体类
        :return: 返回增加的ID
        """
        print(info)
        return cls.dal().addOutProc(info)

    def editSql(cls,info:SchoolInfo) -> int:
        """

        :param info:实体类
        :return:
        """
        #print(info)
        return cls.dal().editSql(info)

    def edit(self,info:SchoolInfo) -> int:
        """

        :param info:实体类
        :return:
        """
        #print(info)
        return self.dal().editSql(info)

    def editProc(cls, info: SchoolInfo) -> int:
        """

        :param info:实体类
        :return:
        """
        return cls.dal().editProc(info)

    def delSql(cls, SchoolId: str) -> int:
        """

        :param SchoolId:
        :return:
        """
        return cls.dal().delSql(SchoolId)

    def delinfo(self, SchoolId: str) -> int:
        """

        :param SchoolId:
        :return:
        """
        return self.dal().delSql(SchoolId)

    def delProc(cls, SchoolId:str) -> int:
        """

        :param SchoolId:
        :return:
        """
        return cls.dal().delProc(SchoolId)

  

 

标签:info,Layer,SchoolId,return,Python,self,python,def,cls
From: https://www.cnblogs.com/geovindu/p/18531195

相关文章

  • python+flask计算机毕业设计个人旅游笔记服务端(程序+开题+论文)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容一、选题背景关于旅游笔记的研究,现有研究主要以旅游目的地的推广、旅游攻略的撰写为主。专门针对个人旅游笔记,从其涵盖的多种系统功能角度进行深入......
  • python+flask计算机毕业设计公共交通查询系统(程序+开题+论文)
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容一、选题背景关于公共交通查询系统的研究,现有研究主要以通用的交通查询功能开发为主,如一些常见的线路查询、站点查询等功能的实现。专门针对提升公......
  • python统计字符串中单个字符出现次数
    str='skdaskerkjsalkj'list=[]foriinrange(len(str)):list.append(str[i])list2=sorted(list)print(list2)foriinrange(len(list)):flag2=Falsest=list2[i]k=i-1#是不是第一个whilek>=0:if(li......
  • 李沐《动手学深度学习》softmax回归python代码实现
    一、手动实现softmax回归#手动实现softmax回归#%matplotlibinlineimporttorchfromd2limporttorchasd2limportmatplotlib.pyplotaspltfromIPythonimportdisplay#参数初始化:batch_size=256train_iter,test_iter=d2l.load_data_fashion_mnist(batc......
  • 李沐《动手学深度学习》权重衰退(正则化)python代码实现
    一、L2正则化手动实现#权重衰退手动实现%matplotlibinlineimporttorchfromd2limporttorchasd2lfromtorchimportnn#n_train个训练样本,n_test个测试样本,输入数据维度是200维n_train,n_test,num_inputs,batch_size=20,200,200,5true_w,true_b=to......
  • 李沐《动手学深度学习》多层感知机python代码实现
    一、多层感知机手动实现#多层感知机的手动实现%matplotlibinlineimporttorchfromtorchimportnnfromd2limporttorchasd2lbatch_size=256train_iter,test_iter=d2l.load_data_fashion_mnist(batch_size)num_inputs,num_outputs,num_first_hiddens=......
  • 李沐《动手学深度学习》线性回归python代码实现
    一、手动实现线性回归#线性回归的手动实现%matplotlibinlineimporttorchimportrandomfromd2limporttorchasd2l#随机按照参数w和b外加一些噪音来创造训练数据集data和labelsdefsynthetic_data(w,b,num_examples):X=torch.normal(0,1,(num_example......
  • Python学习笔记-生成器的应用与原理
    生成器是Python中一种特殊的迭代工具,通过延迟计算的方式来逐步生成序列中的元素。这种特性使得生成器在处理大数据、无限序列或需要惰性求值的场景中十分有效。生成器的核心思想是通过yield语句逐步返回值,暂停并保留当前状态,直到下次调用继续执行,从而节省内存并优化性能......
  • Python学习笔记-断点操作结合异常处理
    在编程中,调试和错误处理是提升代码质量和开发效率的关键环节。调试能帮助识别并修复问题,异常处理则使得程序能在出现错误时有效地管理而不至于崩溃。断点与异常处理的结合应用是高级编程中不可或缺的技巧,能够帮助更高效地定位问题,提高程序的鲁棒性。本文将通过详细的断点和......
  • Python——数据结构与算法-时间复杂度&空间复杂度-链表&树状结构
    1.数据结构和算法简介程序可以理解为:程序=数据结构+算法概述/目的:都可以提高程序的效率(性能)数据结构指的是存储,组织数据的方式.算法指的是为了解决实际业务问题而思考思路和方法,就叫:算法.2.算法的5大特性介绍概述:为了解决实际业务问题,......