Python对数据库实现增删查改

Python对数据库实现增删查改

此版本是控制台版本
先来写个基础类
我使用的数据库 pymsql
dbHelper 数据库连接工具类

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

import pymysql


class DbHelper(object):

    def __init__(self):
        # 获得mysql的连接对象
        self.conn = pymysql.connect(host="localhost", user="root", password="p@ssw0rd", database="test", charset="utf8")
        self.cursor = self.conn.cursor()

    def close(self):
        self.cursor.close()
        self.conn.close()


if __name__ == "  main  ":
    dbHelper = DbHelper()
    print(dbHelper.conn)

dept 实体类

"""
部门实体类
"""

class Dept(object):

    def __init__(self,did,dname,dempnums):
        self.did = did
        self.dname = dname
        self.dempnums = dempnums

    def __str__(self):
        return f"{self.did},{self.dname},{self.dempnums},"


if __name__ == " main ":
    dept = Dept(1, "研发部", 20)
    print(dept)

dao方法
DeptDao

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


class DeptDao(object):

    def __init__(self):
        self.dbHelper = DbHelper()

    # 静态方法  控制台输出语句
    @staticmethod
    def choiceFunc():
        print("*" * 20)
        print("1.添加部门")
        print("2.删除部门")
        print("3.修改部门")
        print("4.查询单个部门")
        print("5.添加所有部门")
        print("6.退出")
        print("*" * 20)

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

    def deleteDept(self, did):
        try:
            self.dbHelper = DbHelper()
            count = self.dbHelper.cursor.execute("delete from dept where did = %s", (did,))
            self.dbHelper.conn.commit()
            return count
        except Exception as result:
            print(result)
            self.dbHelper.conn.rollback()
            print("删除操作异常")
        finally:
            self.dbHelper.close()
            return count

    def updateDept(self, dept):
        try:
            self.dbHelper = DbHelper()
            count = self.dbHelper.cursor.execute("update dept set dname = %s, dempnums = %s where did = %s", (dept.dname, dept.dempnums, dept.did))
            self.dbHelper.conn.commit()
            return count
        except Exception as result:
            print(result)
            self.dbHelper.conn.rollback()
            print("修改信息异常")
        finally:
            self.dbHelper.close()
            return count




    def getAllDepts(self):
        self.dbHelper = DbHelper()
        self.depts = []
        self.dbHelper.cursor.execute("select * from dept")
        for dept in self.dbHelper.cursor.fetchall():
            dept = Dept(dept[0],dept[1],dept[2])
            self.depts.append(dept)

        return self.depts

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

对所有dao方法进行测试,没有问题的话,就直接写控制台语句了

# 测试所有方法
if __name__ == "__main__":
    deptDao = DeptDao()

    # 增加部门
    # dept = Dept(10, "人事部", 20)
    # count = deptDao.addDept(dept)
    # if count > 0:
    #     print(count)
    # else:
    #     print("增加失败")

    # 修改部门
    # dept = Dept(2, "商务部2", 20)
    # count = deptDao.updateDept(dept)
    # if count > 0:
    #     print(count)
    # else:
    #     print("修改失败")

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

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

    # 查询单个部门
    # count = deptDao.getDeptById(2)
    # if count != "":
    #     print(count)
    # else:
    #     print("没有这个部门")

最后直接上控制台

from dao.deptDao 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(3, dname, dempnums)
       count = deptDao.addDept(dept)
       if count > 0:
           print("添加成功")
       else:
           print("添加失败")
    elif num == 2:
        did = int(input("请输入要添加的部门编号:"))
        count = deptDao.deleteDept(did)
        if count > 0:
            print("删除成功")
        else:
            print("删除失败")
    elif num == 3:
        did = int(input("请输入要修改的部门编号:"))
        count = deptDao.getDeptById(did)
        if count != "":
            print(count)
            dname = input("请输入要修改的部门名称:")
            dempnums = input("请输入要修改的部门人数:")
            dept = Dept(did, dname, dempnums)
            updatecg = deptDao.updateDept(dept)
            if updatecg > 0:
                print("修改成功")
            else:
                print("修改失败")
        else:
            print("没有这个部门")
    elif num == 4:
        did = input("请输入要查询的部门编号:")
        count = deptDao.getDeptById(did)
        if count != "":
            print(count)
        else:
            print("没有这个部门")
    elif num == 5:
       depts = deptDao.getAllDepts()
       for dept in depts:
           print(dept)
    elif num == 6:
        print("谢谢使用")
        break
    else:
        print("请输入正确的数字")

看效果
Python对数据库实现增删查改_第1张图片
删除
Python对数据库实现增删查改_第2张图片
修改
Python对数据库实现增删查改_第3张图片
查询所有数据
Python对数据库实现增删查改_第4张图片
查询单个部门
Python对数据库实现增删查改_第5张图片

over~~~

你可能感兴趣的:(Python,Python)