iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >Python MySQL数据库基本操作及项目示例分析
  • 146
分享到

Python MySQL数据库基本操作及项目示例分析

2023-06-25 22:06:12 146人浏览 泡泡鱼
摘要

这篇文章主要介绍“python MySQL数据库基本操作及项目示例分析”,在日常操作中,相信很多人在Python Mysql数据库基本操作及项目示例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对

这篇文章主要介绍“python MySQL数据库基本操作及项目示例分析”,在日常操作中,相信很多人在Python Mysql数据库基本操作及项目示例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Python mysql数据库基本操作及项目示例分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一、数据库基础用法

要先配置环境变量,然后cmd安装:pip install pymysql

连接MySQL,并创建wzg库

#引入decimal模块import pymysql#连接数据库db=pymysql.connect(host='localhost',user='root',passWord='1234',charset='utf8')#创建一个游标对象(相当于指针)cursor=db.cursor()#执行创建数据库语句cursor.execute('create schema wzg default charset=utf8;')cursor.execute('show databases;')#fetchone获取一条数据(元组类型)print(cursor.fetchone())#现在指针到了[1]的位置#fetchall获取全部数据(字符串类型)all=cursor.fetchall()for i in all:    print(i[0])#关闭游标和数据库连接cursor.close()db.close()

创建student表,并插入数据

import pymysql#连接数据库,并打开wzg数据库(数据库已创建)db=pymysql.connect(host='localhost',user='root',password='1234',charset='utf8',db='wzg')#创建游标对象cursor=db.cursor()try:    #创建student表,并执行    sql='''create table student(       SNO char(10),       SNAME varchar(20) NOT NULL,       SSEX varchar(1),       primary key(SNO)       )default charset=utf8;'''    cursor.execute(sql)    #插入一条数据,并执行    insert_sql='''    insert into student values('200303016','王智刚','男'),('20030001','小明','男')    '''    cursor.execute(insert_sql)    #将数据提交给数据库(加入数据,修改数据要先提交)    db.commit()    #执行查询语句    cursor.execute('select * from student')    #打印全部数据    all=cursor.fetchall()    for i in all:        print(i)#发生错误时,打印报错原因except Exception as e:    print(e)#无论是否报错都执行finally:    cursor.close()    db.close()

数据库中char和varchar的区别:

char类型的长度是固定的,varchar的长度是可变的。

例如:存储字符串'abc',使用char(10),表示存储的字符将占10个字节(包括7个空字符),

使用varchar(10),表示只占3个字节,10是最大值,当存储的字符小于10时,按照实际的长度存储。

二、项目:银行管理系统

完成功能:1.查询 2.取钱 3.存钱 4.退出

练习:创建信息表,并进行匹配

创建数据库为(bank),账户信息表为(account)

account_id(varchar(20))Account_passwd(char(6))Money(decimal(10,2))
0011234561000.00
0024567895000.00

拓展:进行账号和密码的匹配

请输入账号:001

请输入密码:123456

select * from account where account_id=001 and Account_passwd=123456if cursor.fetchall():登录成功else:登录失败
import pymysql# 连接数据库db = pymysql.connect(host='localhost', user='root', password='1234', charset='utf8')cursor = db.cursor()# 创建bank库cursor.execute('create database bank charset utf8;')cursor.execute('use bank;')try:    # # 创建表    # sql = '''create table account(    #    account_id varchar(20) NOT NULL,    #    account_passwd char(6) NOT NULL,    #    money decimal(10,2),    #    primary key(account_id)    #    );'''    # cursor.execute(sql)    # # 插入数据    # insert_sql = '''    # insert into account values('001','123456',1000.00),('002','456789',5000.00)    # '''    # cursor.execute(insert_sql)    # db.commit()    # # 查询所有数据    # cursor.execute('select * from account')    # all = cursor.fetchall()    # for i in all:    #     print(i)    # 输入账号和密码    z=input("请输入账号:")    m=input("请输入密码:")        # 从account表中进行账号和密码的匹配    cursor.execute('select * from account where account_id=%s and account_passwd=%s',(z,m))        # 如果找到,则登录成功    if cursor.fetchall():        print('登录成功')    else:        print('登录失败')except Exception as e:    print(e)finally:    cursor.close()    db.close()

1、进行初始化操作

import pymysql# 创建bank库CREATE_SCHEMA_SQL='''    create schema bank charset utf8;    '''# 创建account表CREATE_TABLE_SQL = '''    create table account(    account_id varchar(20) NOT NULL,    account_passwd char(6) NOT NULL,    # decimal用于保存精确数字的类型,decimal(10,2)表示总位数最大为12位,其中整数10位,小数2位    money decimal(10,2),    primary key(account_id)    ) default charset=utf8;    '''# 创建银行账户CREATE_ACCOUNT_SQL = '''    insert into account values('001','123456',1000.00),('002','456789',5000.00);    '''    # 初始化def init():    try:        DB = pymysql.connect(host='localhost',user='root',password='1234',charset='utf8')        cursor1 = DB.cursor()        cursor1.execute(CREATE_SCHEMA_SQL)        DB = pymysql.connect(host='localhost',user='root',password='1234',charset='utf8',database='bank')        cursor2 = DB.cursor()        cursor2.execute(CREATE_TABLE_SQL)        cursor2.execute(CREATE_ACCOUNT_SQL)        DB.commit()        print('初始化成功')        except Exception as e:    print('初始化失败',e)finally:    cursor1.close()    cursor2.close()    DB.close()          # 不让别人调用if __name__ == "__main__":    init()

2、登录检查,并选择操作

import pymysql# 定义全局变量为空DB=None# 创建Account类class Account():    # 传入参数    def __init__(self,account_id,account_passwd):        self.account_id=account_id        self.account_passwd=account_passwd            # 登录检查    def check_account(self):        cursor=DB.cursor()        try:            # 把输入账号和密码进行匹配(函数体内部传入参数用self.)            SQL="select * from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)            cursor.execute(SQL)                        # 匹配成功返回True,失败返回False            if cursor.fetchall():                return True            else:                return False        except Exception as e:            print("错误原因:",e)        finally:            cursor.close()    # 查询余额    # def query_money        # 取钱    # def reduce_money        # 存钱    # def add_money    def main():    # 定义全局变量    global DB        # 连接bank库    DB=pymysql.connect(host="localhost",user="root",passwd="1234",database="bank")    cursor=DB.cursor()        # 输入账号和密码    from_account_id=input("请输入账号:")    from_account_passwd=input("请输入密码:")        # 输入的参数传入给Account类,并创建account对象    account=Account(from_account_id,from_account_passwd)        # 调用check_account方法,进行登录检查    if account.check_account():        choose=input("请输入操作:\n1、查询余额\n2、取钱\n3、存钱\n4、取卡\n")        # 当输入不等于4的时候执行,等于4则退出        while choose!="4":            # 查询            if choose=="1":                print("111")            # 取钱            elif choose=="2":                print("222")            # 存钱            elif choose=="3":                print("333")            # 上面操作完成之后,继续输入其他操作            choose = input("请输入操作:\n1、查询余额\n2、取钱\n3、存钱\n4、取卡\n")        else:            print("谢谢使用!")    else:        print("账号或密码错误")    DB.close()main()

3、加入查询功能

存在银行里的钱可能会产生利息,所以需要考虑余额为小数的问题,需要用到decimal库

import pymysql# 引入decimal模块import decimalDB=Noneclass Account():    def __init__(self,account_id,account_passwd):        self.account_id=account_id        self.account_passwd=account_passwd    # 登录检查    def check_account(self):        cursor=DB.cursor()        try:            SQL="select * from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)            cursor.execute(SQL)            if cursor.fetchall():                return True            else:                return False        except Exception as e:            print("错误",e)        finally:            cursor.close()    # 查询余额    def query_money(self):        cursor=DB.cursor()        try:            # 匹配账号密码,并返回money            SQL="select money from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)            cursor.execute(SQL)            money=cursor.fetchone()[0]            # 如果账户有钱就返回金额,没钱返回0.00            if money:                # 返回值为decimal类型,quantize函数进行四舍五入,'0.00'表示保留两位小数                return str(money.quantize(decimal.Decimal('0.00')))            else:                return 0.00        except Exception as e:            print("错误原因",e)        finally:            cursor.close()def main():    global DB    DB=pymysql.connect(host="localhost",user="root",passwd="1234",charset="utf8",database="bank")    cursor=DB.cursor()    from_account_id=input("请输入账号:")    from_account_passwd=input("请输入密码:")    account=Account(from_account_id,from_account_passwd)    if account.check_account():        choose=input("请输入操作:\n1、查询余额\n2、取钱\n3、存钱\n4、取卡\n")        while choose!="4":            # 查询            if choose=="1":                # 调用query_money方法                print("您的余额是%s元" % account.query_money())            # 取钱            elif choose=="2":                print("222")            # 存钱            elif choose=="3":                print("333")            choose = input("请输入操作:\n1、查询余额\n2、取钱\n3、存钱\n4、取卡\n")        else:            print("谢谢使用")    else:        print("账号或密码错误")    DB.close()main()

4、加入取钱功能

取钱存钱要用update来执行数据库,还要注意取钱需要考虑余额是否充足的问题

import pymysqlimport decimalDB=Noneclass Account():    def __init__(self,account_id,account_passwd):        self.account_id=account_id        self.account_passwd=account_passwd    # 登录检查    def check_account(self):        cursor=DB.cursor()        try:            SQL="select * from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)            cursor.execute(SQL)            if cursor.fetchall():                return True            else:                return False        except Exception as e:            print("错误",e)        finally:            cursor.close()    # 查询余额    def query_money(self):        cursor=DB.cursor()        try:            SQL="select money from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)            cursor.execute(SQL)            money=cursor.fetchone()[0]            if money:                return str(money.quantize(decimal.Decimal('0.00')))            else:                return 0.00        except Exception as e:            print("错误原因",e)        finally:            cursor.close()    # 取钱(注意传入money参数)    def reduce_money(self,money):        cursor = DB.cursor()        try:            # 先调用query_money方法,查询余额            has_money=self.query_money()                        # 所取金额小于余额则执行(注意类型转换)            if decimal.Decimal(money) <= decimal.Decimal(has_money):                            # 进行数据更新操作                SQL="update account set money=money-%s where account_id=%s and account_passwd=%s" %(money,self.account_id,self.account_passwd)                cursor.execute(SQL)                                # rowcount进行行计数,行数为1则将数据提交给数据库                if cursor.rowcount==1:                    DB.commit()                    return True                else:                    # rollback数据库回滚,行数不为1则不执行                    DB.rollback()                    return False            else:                print("余额不足")        except Exception as e:            print("错误原因",e)        finally:            cursor.close()                # 存钱    # def add_moneydef main():    global DB    DB=pymysql.connect(host="localhost",user="root",passwd="1234",charset="utf8",database="bank")    cursor=DB.cursor()    from_account_id=input("请输入账号:")    from_account_passwd=input("请输入密码:")    account=Account(from_account_id,from_account_passwd)    if account.check_account():        choose=input("请输入操作:\n1、查询余额\n2、取钱\n3、存钱\n4、取卡\n")        while choose!="4":            # 查询            if choose=="1":                print("您的余额是%s元" % account.query_money())            # 取钱            elif choose=="2":                # 先查询余额,再输入取款金额,防止取款金额大于余额                money=input("您的余额是%s元,请输入取款金额" % account.query_money())                # 调用reduce_money方法,money不为空则取款成功                if account.reduce_money(money):                    print("取款成功,您的余额还有%s元" % account.query_money())                else:                    print("取款失败!")            # 存钱            elif choose=="3":                print("333")            choose = input("请输入操作:\n1、查询余额\n2、取钱\n3、存钱\n4、取卡\n")        else:            print("谢谢使用!")    else:        print("账号或密码错误")    DB.close()main()

5、加入存钱功能

存钱功能和取钱功能相似,而且不需要考虑余额的问题,至此已完善当前所有功能 

import pymysqlimport decimalDB=Noneclass Account():    def __init__(self,account_id,account_passwd):        self.account_id=account_id        self.account_passwd=account_passwd    # 登录检查    def check_account(self):        cursor=DB.cursor()        try:            SQL="select * from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)            cursor.execute(SQL)            if cursor.fetchall():                return True            else:                return False        except Exception as e:            print("错误",e)        finally:            cursor.close()    # 查询余额    def query_money(self):        cursor=DB.cursor()        try:            SQL="select money from account where account_id=%s and account_passwd=%s" %(self.account_id,self.account_passwd)            cursor.execute(SQL)            money=cursor.fetchone()[0]            if money:                return str(money.quantize(decimal.Decimal('0.00')))            else:                return 0.00        except Exception as e:            print("错误原因",e)        finally:            cursor.close()    # 取钱    def reduce_money(self,money):        cursor = DB.cursor()        try:            has_money=self.query_money()            if decimal.Decimal(money) <= decimal.Decimal(has_money):                SQL="update account set money=money-%s where account_id=%s and account_passwd=%s" %(money,self.account_id,self.account_passwd)                cursor.execute(SQL)                if cursor.rowcount==1:                    DB.commit()                    return True                else:                    DB.rollback()                    return False            else:                print("余额不足")        except Exception as e:            print("错误原因",e)        finally:            cursor.close()    # 存钱    def add_money(self,money):        cursor = DB.cursor()        try:            SQL="update account set money=money+%s where account_id=%s and account_passwd=%s" %(money,self.account_id,self.account_passwd)            cursor.execute(SQL)            if cursor.rowcount==1:                DB.commit()                return True            else:                DB.rollback()                return False        except Exception as e:            DB.rollback()            print("错误原因",e)        finally:            cursor.close()def main():    global DB    DB=pymysql.connect(host="localhost",user="root",passwd="1234",charset="utf8",database="bank")    cursor=DB.cursor()    from_account_id=input("请输入账号:")    from_account_passwd=input("请输入密码:")    account=Account(from_account_id,from_account_passwd)    if account.check_account():        choose=input("请输入操作:\n1、查询余额\n2、取钱\n3、存钱\n4、取卡\n")        while choose!="4":            # 查询            if choose=="1":                print("您的余额是%s元" % account.query_money())            # 取钱            elif choose=="2":                money=input("您的余额是%s元,请输入取款金额" % account.query_money())                if account.reduce_money(money):                    print("取款成功,您的余额还有%s元" % account.query_money())                else:                    print("取款失败!")            # 存钱            elif choose=="3":                money=input("请输入存款金额:")                if account.add_money(money):                    print("存款成功,您的余额还有%s元,按任意键继续\n" % (account.query_money()))                else:                    print("存款失败,按任意键继续")            choose = input("请输入操作:\n1、查询余额\n2、取钱\n3、存钱\n4、取卡\n")        else:            print("谢谢使用!")    else:        print("账号或密码错误")    DB.close()main()

到此,关于“Python MySQL数据库基本操作及项目示例分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!

您可能感兴趣的文档:

--结束END--

本文标题: Python MySQL数据库基本操作及项目示例分析

本文链接: https://www.lsjlt.com/news/306352.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python MySQL数据库基本操作及项目示例分析
    这篇文章主要介绍“Python MySQL数据库基本操作及项目示例分析”,在日常操作中,相信很多人在Python MySQL数据库基本操作及项目示例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对...
    99+
    2023-06-25
  • PythonMySQL数据库基本操作及项目示例详解
    目录一、数据库基础用法二、项目:银行管理系统1、进行初始化操作2、登录检查,并选择操作3、加入查询功能4、加入取钱功能5、加入存钱功能一、数据库基础用法 要先配置环境变量,然后cmd...
    99+
    2024-04-02
  • MySQL数据库基本操作的示例分析
    这篇文章主要介绍了MySQL数据库基本操作的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。一、数据库的安装这个就不在这里过多阐述了,...
    99+
    2024-04-02
  • MySQL数据库的基本操作实例分析
    本文小编为大家详细介绍“MySQL数据库的基本操作实例分析”,内容详细,步骤清晰,细节处理妥当,希望这篇“MySQL数据库的基本操作实例分析”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。一、MySQL简介1、数据...
    99+
    2023-06-30
  • Mysql数据库中基本操作示例
    小编给大家分享一下Mysql数据库中基本操作示例,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一. 库的操作1.创建数据库创建数...
    99+
    2024-04-02
  • MongoDB数据库基础操作的示例分析
    这篇文章将为大家详细讲解有关MongoDB数据库基础操作的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。为了保存网站的用户数据和业务数据,通常需要一个数据库。Mo...
    99+
    2024-04-02
  • MongoDB数据库安装配置、基本操作的示例分析
    小编给大家分享一下MongoDB数据库安装配置、基本操作的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!具体如下:1、简...
    99+
    2024-04-02
  • MySQL基本操作和基于MySQL基本操作的综合实例项目
    文章目录 MySQL数据库的基本操作和基于MySQL数据库基本操作的综合实例项目1、 登入MySQL数据库1、创建数据库2、删除数据库3、综合案例——数据库的创建和删除cmd环境创建和删除数据...
    99+
    2023-09-04
    mysql 数据库 sql ide 数据库开发
  • MySQL数据库常用操作的示例分析
    小编给大家分享一下MySQL数据库常用操作的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!具体如下:一、查询不同表中同名...
    99+
    2024-04-02
  • Java基础之JDBC连接数据库与基本操作的示例分析
    小编给大家分享一下Java基础之JDBC连接数据库与基本操作的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!Java可以用来干什么Java主要应用于:1....
    99+
    2023-06-14
  • JavaScript数组基本操作的示例分析
    这篇文章主要为大家展示了“JavaScript数组基本操作的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“JavaScript数组基本操作的示例分析”这篇文章吧。一、初识数组数组构成:数...
    99+
    2023-06-29
  • MySQL数据库基本操作
    目录 一、SQL语句 (mysql 数据库中的语言) 二、DDL 1.DDL语句 (1)创建新的数据库 (2)创建新的表  2.删除数据库和表  三、DML 1.insert插入新数据 2.update更新原有数据 3.delete: 删除...
    99+
    2023-09-01
    数据库 mysql sql
  • mysql中数据表基本操作的示例
    这篇文章主要介绍mysql中数据表基本操作的示例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!案例:创建数据库company,按照下面两个表给出的表结构在company数据库中创建两...
    99+
    2024-04-02
  • mysql中数据操作的示例分析
    这篇文章给大家分享的是有关mysql中数据操作的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。1、读取数据select * from tb1;select...
    99+
    2023-06-15
  • Linux---连接mysql数据库以及基本操作
    文章目录 一、连接MySQL二、MySQL的基本操作1.查询已有数据库2.创建数据库3.选定数据库4.查询数据库下的表5.查询表结构6.查询当前用户7.查询当前选择数据库8.删除数据库9.创建表10.插入表数据11.查询表数据12....
    99+
    2023-08-24
    数据库 mysql linux
  • mysql数据库基本语法及操作大全
    mysql数据库基本语法 DDL操作 创建数据库 语法:create database 数据库名; 查看所有数据库 语法:show databases; 切换(使用)数据库 语法:u...
    99+
    2024-04-02
  • MySQL-Workbench数据库基本操作
    注: 部分概念介绍来源于网络 一、连接数据库 二、进入数据库   三、创建数据库         点击创建数据库按钮,输入数据库名称,选择编码方式,点击Apply。         Workbench会自动生成SQL语句,再次点击A...
    99+
    2023-10-12
    mysql
  • MySQL数据库中表查询操作的示例分析
    小编给大家分享一下MySQL数据库中表查询操作的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!一、单表查询      1...
    99+
    2024-04-02
  • 数据库初始化及数据库服务端操作的示例分析
    这篇文章将为大家详细讲解有关数据库初始化及数据库服务端操作的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。为什么要学习数据库?数据库的好处:实现持久化数据到本地使用完整的管理系统统一管理,易于查询...
    99+
    2023-06-21
  • MySQL数据库监控项的示例分析
    这篇文章将为大家详细讲解有关MySQL数据库监控项的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。 监控项目 MYSQL.QPS &...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作