Python——连接数据库操作
一、数据库基础用法
要先配置环境变量,然后cmd安装:pip install pymysql
1、连接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()
2、创建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.退出
练习:创建信息表,并进行匹配
1、创建数据库为(bank),账户信息表为(account)
account_id(varchar(20)) | Account_passwd(char(6)) | Money(decimal(10,2)) |
---|---|---|
001 | 123456 | 1000.00 |
002 | 456789 | 5000.00 |
2、拓展:进行账号和密码的匹配
请输入账号:001
请输入密码:123456
select * from account where account_id=001 and Account_passwd=123456
if 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_idself.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,失败返回Falseif cursor.fetchall():return Trueelse:return Falseexcept Exception as e:print("错误原因:",e)finally:cursor.close()# 查询余额# def query_money# 取钱# def reduce_money# 存钱# def add_moneydef 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 decimal DB=None class Account():def __init__(self,account_id,account_passwd):self.account_id=account_idself.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 Trueelse:return Falseexcept Exception as e:print("错误",e)finally:cursor.close()# 查询余额def query_money(self):cursor=DB.cursor()try:# 匹配账号密码,并返回moneySQL="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.00if money:# 返回值为decimal类型,quantize函数进行四舍五入,'0.00'表示保留两位小数return str(money.quantize(decimal.Decimal('0.00')))else:return 0.00except Exception as e:print("错误原因",e)finally:cursor.close()def main():global DBDB=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 pymysql import decimal DB=None class Account():def __init__(self,account_id,account_passwd):self.account_id=account_idself.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 Trueelse:return Falseexcept 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.00except 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 Trueelse:# rollback数据库回滚,行数不为1则不执行DB.rollback()return Falseelse:print("余额不足")except Exception as e:print("错误原因",e)finally:cursor.close()# 存钱# def add_moneydef main():global DBDB=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 pymysql import decimal DB=None class Account():def __init__(self,account_id,account_passwd):self.account_id=account_idself.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 Trueelse:return Falseexcept 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.00except 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 Trueelse:DB.rollback()return Falseelse: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 Trueelse:DB.rollback()return Falseexcept Exception as e:DB.rollback()print("错误原因",e)finally:cursor.close()def main():global DBDB=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——连接数据库操作相关推荐
- python自带模块连接数据库_Python使用sqlalchemy模块连接数据库操作示例
本文实例讲述了Python使用sqlalchemy模块连接数据库操作.分享给大家供大家参考,具体如下: 安装: pip install sqlalchemy # 安装数据库驱动: pip instal ...
- python处理excel表格实例-通过实例学习Python Excel操作
这篇文章主要介绍了通过实例学习Python Excel操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.python 读取Excel # -* ...
- 使用python连接数据库
#使用python连接数据库 import pymysql #第一步:连接数据库 conn=pymysql.connect(host='ip地址',port=端口,user='账号',passwd=' ...
- python数据库操作之pymysql模块和sqlalchemy模块(项目必备)
pymysql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 1.下载安装 pip3 install pymysql 2.操作数据库 (1).执行sql #! ...
- Python中操作MySQL/Oracle
Python中操作MySQL/Oracle 一.Python操作数据库介绍 二.Python操作MySQL 2.1 PySQL模块 2.1.1 安装PyMySQL 2.2 基本使用 2.3 获取最新创 ...
- python通过什么连接数据库_如何使用python连接数据库?
数据分析离不开数据库,如何使用python连接数据库呢?听我娓娓道来哈 该笔记参考了PyMySQL官方文档和<python数据采集>关于数据存储的部分,欢迎大家去阅读原著,相信会理解的更加 ...
- 【数据库】python连接数据库(保姆式服务,一口一口喂啊歪)
博主用的是:MySQL.Navicat Premium 15(连接数据库开发工具) 博主在连接数据库彻底疯狂后,终于搭建成功了.(强烈建议用mysql+pycharm+Navicat Premium ...
- python数据库操作——连接SQLite
python数据库操作--连接SQLite hello!我是wakeyo_J,每天一个konwledge point,一起学python,让技术无限发散. 连接SQLite python数据库操作 ...
- 【Python】Python 2 和 Python 3 操作 MySQL 数据库实现创建表、删除表、增删改查操作
1.MySQL数据库和表的编码格式 (1)创建数据库并指定字符集 mysql> create database testpythondb character set utf8; Query OK ...
最新文章
- setBackgroundResource和setImageResource的区别
- vivado2017.4安装教程
- JVM内存管理机制和垃圾回收机制
- 从起源到未来:能自己编程和改进的超人工智能会出现吗?
- 华为正式开源数据虚拟化引擎 openLooKeng
- H5 input type=“search“ 不显示搜索 解决方法
- 小程序模拟服务器,小程序模拟请求服务器json数据
- python拉格朗日插值法_【统计学】拉格朗日插值法的一种python实现方式
- vue 如何处理两个组件异步问题_Vue异步组件处理路由组件加载状态的解决方案...
- 2 创建型模式之 - 工厂模式
- c语言的编译器还真是不好理解...
- php vue是什么,vue.js是什么软件
- 做了6年的Java,java简历包装项目经验
- Android中可展开的列表组件(ExpandableListView)的使用
- 江西师范大学教育心理测量计算机,江西师范大学重点和特色专业介绍
- 硬核观察 #612 谷歌正式推出“切换到安卓”应用
- 【2022-05-31】JS逆向之易企秀
- jvm调优【减少GC频率和Full GC次数】中Gc是什么
- 感恩节和感恩节的由来!
- 洛谷入门篇的相关题解
热门文章
- jquery水平导航栏动态菜单
- 金山云VR+8K超高清直播全链路解决方案
- 双开助手多开分身版 v5.1.8
- lumen php版本,PHP微框架 Lumen 使用全纪录
- 如何配置一台深度学习的主机
- 三菱PLC控制东芝4轴机器人程序,有完整的PLC程序带注释
- kettle web 版本 (webspoon) 中文部署 kettle 页面编辑 kettleweb 中文
- Qt如何自适应4k这些高分辨率屏幕
- python中xpath使用案例_python爬虫学习笔记:XPath语法和使用示例
- android lcd 显示图片,Android开发中通过AIDL文件中的方法打开钱箱,显示LCD屏幕