Python(mySql)数据库的增删查改

@toc
目录
在这里插入图片描述

entity

dept

"""
部门实体类
"""

class Dept(object):
#初始化方法
    def __init__(self, did, dname, dempnums):
        self.did = did
        self.dname = dname
        self.dempnums = dempnums
#相当于Java里面的toString方法
    def __str__(self):
        return f"{self.did},{self.dname},f{self.dempnums}"
#测试实体类正确与否
if __name__== "__main__":
    dept = Dept(1, "研发部", "20")
    print(dept)

db

dbHelper

"""
数据库的连接工具类
"""

import pymysql

class DbHelper(object):

    def __init__(self):
# 获取mysql的连接对象
        self.conn = pymysql.connect(host="localhost", user="root", password="123", database="mysql", charset="utf8")
        self.curson = self.conn.cursor()

    # 关闭
    def close(self):
        self.curson.close()
        self.conn.close()
#测试
if __name__ == "__main__":
    dbHelper = DbHelper()
    print(dbHelper.conn)

dao

daptDao

选择功能列表

# 选择功能列表
    @staticmethod
    def choiceFunc():
        print("*" * 20)
        print("1.添加部门")
        print("2.删除部门")
        print("3.修改部门")
        print("4.查询部门")
        print("5.查询单个部门")
        print("6.退出")

增加

# 增加
    def addDept(self, dept):
        try:
            self.dbHelper = DbHelper()
            count = self.dbHelper.curson.execute("insert into dept values(null,%s,%s)", (dept.dname, dept.dempnums))
            self.dbHelper.conn.commit()
            return count
        except Exception as result:
            #         有异常的情况下,数据进行回滚操作
            self.dbHelper.conn.rollback()
            print("添加操作异常")
        finally:
            self.dbHelper.close()

测试dao方法是否正确

if __name__ == "__main__":
    deptDao = DeptDao()
    # 增加
    dept = Dept(1, "研发部", 23)
    count = deptDao.addDept(dept)
    if count>0:
        print("增加成功")
    else:
        print("增加失败")

删除

# 删除
    def deleteDept(self, did):
        self.dbHelper = DbHelper()
        try:
            # c.execute("delete from question where _id = ?", (16,))
            count = self.dbHelper.curson.execute("delete from dept where did = %s", (did,))
            self.dbHelper.conn.commit()
            return count
        except:
            self.dbHelper.conn.rollback()
            print("操作异常")
        finally:
            self.dbHelper.close()

测试dao方法是否正确

if __name__ == "__main__":
    deptDao = DeptDao()
   #删除
    count = deptDao.deleteDept(1)
    if count > 0:
        print("删除成功")
    else:
        print("删除失败")

修改

# 修改
    def updateDept(self, dept):
        self.dbHelper = DbHelper()
        try:
            # c.execute("update question set answer = ? where _id = ?", ("C", 1))
            count = self.dbHelper.curson.execute("update dept set dname= %s,dempnums = %s where did = %s",
                                                 (dept.dname, dept.dempnums, dept.did))
            self.dbHelper.conn.commit()
            return count
        except:
            self.dbHelper.conn.rollback()
            print("修改操作异常")
        finally:
            self.dbHelper.close()

测试dao方法是否正确

if __name__ == "__main__":
    deptDao = DeptDao()
   #修改
    dept = Dept(2, "人力资源部", 34)
    count = deptDao.updateDept(dept)
    if count > 0:
        print("修改成功")
    else:
        print("修改失败")

查询所有

# 查询所有
    def getAllDepts(self):
        self.dbHelper = DbHelper()
        self.depts = []
        self.dbHelper.curson.execute("select * from dept")
        for dept in self.dbHelper.curson.fetchall():
            dept = Dept(dept[0], dept[1], dept[2])
            self.depts.append(dept)
        return self.depts

测试dao方法是否正确

if __name__ == "__main__":
    deptDao = DeptDao()
   # 查所有
    depts = deptDao.getAllDepts()
    for dept in depts:
        print(dept)

*** 查询单个***

 # 查询单个
    def getDeptById(self, did):
        self.dbHelper = DbHelper()
        try:
            count = self.dbHelper.curson.execute("select * from dept where did = %s", (did,))
            one = self.dbHelper.curson.fetchone()
            self.dbHelper.conn.commit()
            return one
        except:
            self.dbHelper.conn.rollback()
            print("查询单个操作异常")
        finally:
            self.dbHelper.close()

测试dao方法是否正确

if __name__ == "__main__":
    deptDao = DeptDao()
    # 查询单个
    depts = deptDao.getDeptById(3)
    for dept in depts:
        print(dept)

CRUD

# 导入数据库的工具类
from db.dbhelper import DbHelper
from entity.dept import Dept


class DeptDao(object):

    # 选择功能列表
    @staticmethod
    def choiceFunc():
        print("*" * 20)
        print("1.添加部门")
        print("2.删除部门")
        print("3.修改部门")
        print("4.查询部门")
        print("5.查询单个部门")
        print("6.退出")
    # 增加
    def addDept(self, dept):
        try:
            self.dbHelper = DbHelper()
            count = self.dbHelper.curson.execute("insert into dept values(null,%s,%s)", (dept.dname, dept.dempnums))
            self.dbHelper.conn.commit()
            return count
        except Exception as result:
            #         有异常的情况下,数据进行回滚操作
            self.dbHelper.conn.rollback()
            print("添加操作异常")
        finally:
            self.dbHelper.close()
    # 删除
    def deleteDept(self, did):
        self.dbHelper = DbHelper()
        try:
            # c.execute("delete from question where _id = ?", (16,))
            count = self.dbHelper.curson.execute("delete from dept where did = %s", (did,))
            self.dbHelper.conn.commit()
            return count
        except:
            self.dbHelper.conn.rollback()
            print("操作异常")
        finally:
            self.dbHelper.close()
    # 修改
    def updateDept(self, dept):
        self.dbHelper = DbHelper()
        try:
            # c.execute("update question set answer = ? where _id = ?", ("C", 1))
            count = self.dbHelper.curson.execute("update dept set dname= %s,dempnums = %s where did = %s",
                                                 (dept.dname, dept.dempnums, dept.did))
            self.dbHelper.conn.commit()
            return count
        except:
            self.dbHelper.conn.rollback()
            print("修改操作异常")
        finally:
            self.dbHelper.close()
    # 查询所有
    def getAllDepts(self):
        self.dbHelper = DbHelper()
        self.depts = []
        self.dbHelper.curson.execute("select * from dept")
        for dept in self.dbHelper.curson.fetchall():
            dept = Dept(dept[0], dept[1], dept[2])
            self.depts.append(dept)
        return self.depts
    # 查询单个
    def getDeptById(self, did):
        self.dbHelper = DbHelper()
        try:
            count = self.dbHelper.curson.execute("select * from dept where did = %s", (did,))
            one = self.dbHelper.curson.fetchone()
            self.dbHelper.conn.commit()
            return one
        except:
            self.dbHelper.conn.rollback()
            print("查询单个操作异常")
        finally:
            self.dbHelper.close()

# 测试方法
if __name__ == "__main__":
    deptDao = DeptDao()
    # 查询单个
    # depts = deptDao.getDeptById(3)
    # for dept in depts:
    #     print(dept)

    #删除
    # count = deptDao.deleteDept(1)
    # if count > 0:
    #     print("删除成功")
    # else:
    #     print("删除失败")

    #修改
    # dept = Dept(2, "人力资源部", 34)
    # count = deptDao.updateDept(dept)
    # if count > 0:
    #     print("修改成功")
    # else:
    #     print("修改失败")

    # 查所有
    # depts = deptDao.getAllDepts()
    # for dept in depts:
    #     print(dept)

    # 增加
    # dept = Dept(1, "研发部", 23)
    # count = deptDao.addDept(dept)
    # if count>0:
    #     print("增加成功")
    # else:
    #     print("增加失败")

测试方法main

调用选择功能表

DeptDao.choiceFunc()
from dao.daptDao import DeptDao
from entity.dept import Dept

deptDao = DeptDao()

while True:
    DeptDao.choiceFunc()
    num = int(input("请输入你要输入的操作"))
    if num == 1:
        dname = input("请输入你要添加的部门名称")
        dempnums = input("请输入你要添加的部门人数")
        dept = Dept(0, dname, dempnums)
        count = deptDao.addDept(dept)
        if count > 0:
            print("添加OK")
        else:
            print("添加失败")
    elif num == 2:
        did = input("请输入你要删除的编号")
        count = deptDao.deleteDept(did)
        if count > 0:
            print("删除OK")
        else:
            print("删除失败")
    elif num == 3:
        did = int(input("请输入部门编号:"))
        dname = input("请输入你要修改的部门名称")
        dempnums = input("请输入你要修改的部门人数")
        dept = Dept(did, dname, dempnums)
        count = deptDao.updateDept(dept)
        if count > 0:
            print("修改OK")
        else:
            print("修改失败")
    elif num == 4:
        depts = deptDao.getAllDepts()
        for dept in depts:
            print(dept)
    elif num == 5:
        did = int(input("请输入部门编号:"))
        # dept = Dept(did)
        count = deptDao.getDeptById(did)
        if count != "":
            print(count)
        else:
            print("查询单个失败")
    else:
        print("谢谢使用")
        break
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值