基于python与MySQL的记账可视化小程序

news/2024/7/20 4:20:41 标签: mysql, python, 小程序

最近学习了一下MySQL的操作,顺便写了一个记账并可视化的小程序
                                 数据库设计

IDnamemoneysummoneydatetime

注:该表格在“demo1”数据库下,表格名为:infor

数据库操作类

python">class MySql:
    ###构造函数
    def __init__(self,user,password,database,maineig="localhost"):
        self.db=MySQLdb.connect(maineig,user,password,database,charset='utf8')
    ###查询函数
    def Look(self,sql):
        try:
            cursor = self.db.cursor()  # 使用cursor()方法获取操作游标
            cursor.execute(sql)  # 执行sql语言
            result = cursor.fetchall()  # 获取表中数据,其中result是一个元组
            return result
        except:
            print("SEARCH ERROR!")
    ###插入函数
    def Insert(self,sql):
        try:
            cursor=self.db.cursor()
            cursor.execute(sql)
            self.db.commit()  # 提交到数据库执行
        except:
            self.db.rollback()
            print("INSERT ERROR:已经回滚!")
    ###数据库删除信息
    def Delete(self,sql):
        try:
            cursor=self.db.cursor()
            cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
            print("DELETE ERROR:已经回滚!")
    ###数据库更新信息
    def Update(self,sql):
        try:
            cursor=self.db.cursor()
            cursor.execute(sql)
            self.db.commit()
        except:
            self.db.rollback()
            print("UPDATE ERROR:已经回滚!")
    ###析构函数
    def __del__(self):
        self.db.close()

数据库操作函数

python">def DatabaseConduct(ms):
    start = "+------选择功能-------+\n"
    start += "|     1.添加信息      |\n"
    start += "|     2.删除信息      |\n"
    start += "|     3.修改信息      |\n"
    start += "|     4.查询信息      |\n"
    start += "|     5.退出程序      |\n"
    start += "+---------end---------+\n"
    print(start)
    judge = int(input("请输入执行功能:"))
    while (judge != 5):
        if (judge == 1):
            name = input("请输入姓名:")
            money = float(input("请输入金额:(¥)"))
            summoney = ms.Look("select * from infor")[-1][3] + money
            ID = ms.Look("select * from infor")[-1][0] + 1
            dt =datetime.datetime.now()
            sql1 = """insert into infor (ID,name,money,summoney,datetime) VALUES (""" + str(ID) + " , "+'"' + name + '"'+" , " + str(money) + " , " + str(summoney) + " , " +'''"'''+str(dt)+'''"'''+")"
            ms.Insert(sql1)
        elif (judge == 2):
            id = int(input("请输入要删除的行号:"))
            sql2="delete from infor where ID = "+str(id)
            ms.Delete(sql2)
            res=ms.Look("select * from infor")
            max=len(res)
            for i in range(id,max+2):
                sqli="update infor set ID = "+str(i-1)+" where ID = "+str(i)
                ms.Update(sqli)
        elif (judge == 3):
            id=input("请输入要更改的行号:")
            change = int(input("请选择要更改的字段:1.name; 2.money; 3.summoney; 4.datetime"))
            item=input("请输入更改后的值:")
            sqlj=""
            if(change==1):
               sqlj="update infor set name = "+ '"'+item+'"'+" where ID = "+id
               ms.Update(sqlj)
            elif(change==2):
                sqlj = "update infor set money = " + item  + " where ID = " + id
                ms.Update(sqlj)
                re=ms.Look("select * from infor")
                print(re)
                max=len(re)
                presum = re[int(id) -2][3]
                presum=presum+re[int(id)-1][2]
                for i in range(int(id)-1,max):
                    presum+=re[i][2]
                    Id=i+1
                    sq="update infor set summoney = " + str(presum)  + " where ID = " + str(Id)
                    ms.Update(sq)
            elif(change==3):
                sqlj = "update infor set summoney = " + item + " where ID = " + id
                ms.Update(sqlj)
            elif(change==4):
                sqlj = "update infor set name = " + '"' + item + '"' + " where ID = " + id
                ms.Update(sqlj)
        elif (judge == 4):
            sql = "select * from infor"
            result = ms.Look(sql)
            for i in result:
                print(i)
        print(start)
        judge = int(input("请输入执行功能:"))

可视化

python">def Visual(ms):
    all=ms.Look("select * from infor")
    start = "+------选择功能-------+\n"
    start += "|     1.按年显示      |\n"
    start += "|     2.按月显示      |\n"
    start += "|     3.按日显示      |\n"
    start += "|     4.退出程序      |\n"
    start += "+---------end---------+\n"
    print(start)
    judge = int(input("请输入执行功能:"))
    while (judge !=4):
        if (judge==1):
            strbeginyear=str(all[0][4])[0:4]
            strendyear=str(all[-1][4])[0:4]
            oneyear=int(strbeginyear)
            everymoneys=[]
            summoneys=[]
            thislist = []
            while oneyear <=int(strendyear):
                onest=ms.Look("select * from infor where datetime regexp '"+str(oneyear)+"'")
                if(onest !=()):
                    onemoney = onest[-1][3] - onest[0][3] + onest[0][2]
                    onesum = onest[-1][3]
                    everymoneys.append(onemoney)
                    summoneys.append(onesum)
                    thislist.append(oneyear)
                    oneyear += 1
                else:
                    oneyear+=1
            xtick = (np.arange(len(thislist)))
            plt.subplot()
            matplotlib.rcParams["font.family"] = "KaiTi"
            plt.bar(xtick,everymoneys,0.3,label="各年收支")
            plt.plot(xtick, summoneys, "--r",label="累计收支")
            plt.xlabel("年份",fontproperties="KaiTi",size=14)
            plt.ylabel("金额(¥)",fontproperties="KaiTi",size=14)
            plt.title("各年份收支信息",fontproperties="KaiTi",size=22)
            plt.legend()
            plt.xticks(xtick)
            plt.show()
        elif(judge==2):
            year=input("请输入年份:")
            partyear=ms.Look("select * from infor where datetime regexp '" + year + "'")
            strbeginmonth = str(partyear[0][4])[5:7]
            strendmonth=str(partyear[-1][4])[5:7]
            onemonth = int(strbeginmonth)
            everymoneys = []
            summoneys = []
            monthlist=["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]
            thislist=[]
            monthcount=int(strbeginmonth)
            while onemonth <= int(strendmonth):
                onest = ms.Look("select * from infor where datetime regexp '" +year+"-"+ "0*"+str(onemonth) + "'")
                if(onest !=()):
                    onemoney = onest[-1][3] - onest[0][3] + onest[0][2]
                    onesum = onest[-1][3]
                    everymoneys.append(onemoney)
                    summoneys.append(onesum)
                    thislist.append(monthlist[onemonth-1])
                    onemonth += 1
                else:
                    onemonth += 1
            xtick = (np.arange(len(thislist)))
            plt.subplot()
            matplotlib.rcParams["font.family"] = "KaiTi"
            plt.bar(xtick, everymoneys, 0.3,label="各月收支")
            plt.plot(xtick, summoneys, "--r",label="累计收支")
            plt.xlabel("月份", fontproperties="KaiTi", size=14)
            plt.ylabel("金额(¥)",fontproperties="KaiTi", size=14)
            plt.title(year+"年各月份收支信息", fontproperties="KaiTi", size=22)
            plt.xticks(xtick,thislist,fontproperties="KaiTi",size=14)
            plt.legend()
            plt.show()
        elif (judge==3):
            year  = input("请输入年份:")
            month = input("请输入月份:")
            partmonth = ms.Look("select * from infor where datetime regexp '" + year +"-"+"0*"+month+ "'")
            strbeginday = str(partmonth[0][4])[8:10]
            strendday = str(partmonth[-1][4])[8:10]
            oneday = int(strbeginday)
            everymoneys = []
            summoneys = []
            thislist = []
            daycount = int(strbeginday)
            while oneday <= int(strendday):
                onest = ms.Look("select * from infor where datetime regexp '" + year + "-" + "0*" + month +"-0*"+str(oneday)+ "'")
                if (onest != ()):
                    onemoney = onest[-1][3] - onest[0][3] + onest[0][2]
                    onesum = onest[-1][3]
                    everymoneys.append(onemoney)
                    summoneys.append(onesum)
                    thislist.append(oneday)
                    oneday += 1
                else:
                    oneday += 1
            xtick = (np.arange(len(thislist)))
            plt.subplot()
            matplotlib.rcParams["font.family"] = "KaiTi"
            plt.bar(xtick, everymoneys, 0.3,label="各天收支")
            plt.plot(xtick, summoneys, "--r",label="累计收支")
            plt.xlabel("天", fontproperties="KaiTi", size=14)
            plt.ylabel("金额(¥)", fontproperties="KaiTi", size=14)
            plt.title(year+"年"+month+"月每日收支信息", fontproperties="KaiTi", size=22)
            plt.xticks(xtick, thislist, fontproperties="KaiTi", size=14)
            plt.legend()
            plt.show()
        print(start)
        judge = int(input("请输入执行功能:"))

主函数

python">if __name__=="__main__":
    ms=MySql("root","此处填写数据库密码","demo1")
    DatabaseConduct(ms)
    Visual(ms)

实例

在这里插入图片描述
在这里插入图片描述


http://www.niftyadmin.cn/n/889024.html

相关文章

虚拟机配置ubuntu

一、上网 二、Ubuntu 常用解压与压缩命令 三、切换root 四、安装输入法 https://zhuanlan.zhihu.com/p/111734450 安装输入法 问题解决 用shiftwinspace切换 五、安装VMware Tools 视频 六、虚拟机安装VMware Tools仍旧不能复制粘贴的解决方法–共享文件夹 七、虚拟机安…

QT基础操作

QTVS2017常见问题 子进程或与子进程通讯时出错 项目-》属性 功能测试宏的参数必须是简单标识符 1、点击这个错误可以定位到出问题的代码 2、在这个头文件中把代码修改一下即可&#xff0c;代码如下 #if defined(__cplusplus) #if defined(__clang__) #if QT_HAS_CPP_ATTR…

MATLAB做遥感数字图像处理(1)

基础 编程tip 能用向量不用循环 i1:100; matmat.*15;BIL和BIP运算效率高 &#xff0c;BSQ读取效率高 数组下标是从1开始的&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01; CtrlC 强制退出运行 像素处理一定将 uint8转换为double do…

MATLAB做遥感数字图像处理

基础 编程tip 能用向量不用循环 i1:100; matmat.*15;BIL和BIP运算效率高 &#xff0c;BSQ读取效率高 数组下标是从1开始的&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01; CtrlC 强制退出运行 像素处理一定将 uint8转换为double do…

python如何给键值增加数据_python字典中如何添加键值对

添加键值对首先定义一个空字典>>> dic{}直接对字典中不存在的key进行赋值来添加>>> dic[name]zhangsan>>> dic{name: zhangsan}如果key或value都是变量也可以用这种方法>>> keyage>>> value30>>> dic[key]value>>…

e7用什么主板_主板当中的纽扣电池有什么用?电池没电了会怎样?

只要是购买过主板的朋友都知道&#xff0c;在主板上面有着一款纽扣大小的电池&#xff0c;一般都是位于主板的PCIE插槽附近&#xff0c;并且这个电池是可以被取下来的。现在问题来了&#xff0c;主板电池没电了会怎样&#xff1f;主板电池怎么拆&#xff1f;主板电池多久换一次…

MATLAB做遥感数字图像处理(2)

图像融合 Brovey function brovimg Brovey(mtl,pan) %UNTITLED 此处显示有关此函数的摘要 % 此处显示详细说明 [rows,cols,bands]size(pan); brovimgzeros(rows,cols,bands); mtldouble(mtl(:,1:cols,:)); pandouble(pan(:,:,1)); for band 1:3oneband(pan.*mtl(:,:,band)…

python身份证号提取生日_【Python编程特训连载71】编写一个输入身份证号码即可判断生日的程序...

身份证号码都是唯一的,新二代身份证号码为18位,前6位为籍贯:其中前2位为省区编号,7-10位为出生年,11-12位为出生月,13-14位为出生日期,17位为性别:偶数为女,奇数为男。通过以上规则,根据身份证号码,即可判断所属身份、出生日期和性别,如输入身份证号码“2201052003…