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_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 decimal
DB=None
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:
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 pymysql
import decimal
DB=None
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:
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_money
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())
# 调用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_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——连接数据库操作的更多相关文章
- python 连接数据库操作
import mysql #打开数据库连接(用户名,密码,数据库名) db = mysql.connect("localhost","testuser",&qu ...
- python数据库操作之pymysql模块和sqlalchemy模块(项目必备)
pymysql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同. 1.下载安装 pip3 install pymysql 2.操作数据库 (1).执行sql #! ...
- python/ORM操作详解
一.python/ORM操作详解 ===================增==================== models.UserInfo.objects.create(title='alex ...
- Python中操作ini配置文件
这篇博客我主要想总结一下python中的ini文件的使用,最近在写python操作mysql数据库,那么作为测试人员测试的环境包括(测试环境,UAT环境,生产环境)每次需要连接数据库的ip,端口,都会 ...
- python27期python连接数据库:
import pymysql创建connectinon对象:con = pymysql.connect(host = "localhost",user = "root&q ...
- python连接数据库自动发邮件
python连接数据库实现自动发邮件 1.运行环境 redhat6 + python3.6 + crontab + Oracle客户端 2.用到的模块 3.操作步骤 (1)安装python3.6参考 ...
- Python连接数据库流行用到的第三方库
Python连接数据库流行用到的第三方库: mysqldb:只支持Python2.x mysqlclient : mysqldb的衍生版本,完全兼容mysqldb,同时支持Python3.x,安装较复 ...
- Python中操作mysql的pymysql模块详解
Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...
- Python 字符串操作
Python 字符串操作(string替换.删除.截取.复制.连接.比较.查找.包含.大小写转换.分割等) 去空格及特殊符号 s.strip() .lstrip() .rstrip(',') 复制字符 ...
随机推荐
- 001.AD域控简介及使用
一 AD概述 1.1 AD简介 域(Domain)是Windows网络中独立运行的单位,域之间相互访问则需要建立信任关系. 当一个域与其他域建立了信任关系后,2个域之间不但可以按需要相互进行管理,还可 ...
- Python基础(定制类)
文章转载自廖雪峰老师Python课程博客,仅供学习参考使用看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的. __slots__我们已经知道 ...
- 第十五章---JSON
目录: (一)介绍 (二)Python 编码为 JSON 类型转换对应表 (三)JSON 解码为 Python 类型转换对应表 (四)实例 正文: (一)介绍 JSON (JavaScript Obj ...
- 看动画学算法之:hashtable
目录 简介 散列表的关键概念 数组和散列表 数组的问题 hash的问题 线性探测 二次探测 双倍散列 分离链接 rehash 简介 java中和hash相关并且常用的有两个类hashTable和has ...
- Electron跨平台程序破解
1. npm install asar -g 2. asar --version 如果有版本号就继续 3.找到需要解压的软件位置 在app.asar的地址输入 asar e app.asar tm ...
- 51nod 1709 复杂度分析
51nod 1709 复杂度分析 考虑定义 $ F(x) $ 为 \(x\) 为根的子树所有点与 $ x $ 的深度差(其实就是 $ x $ 到每个子树内点的距离)的 1 的个数和. 注意,$ F(x ...
- 分布式事务(4)---最终一致性方案之TCC
分布式事务(1)-理论基础 分布式事务(2)---强一致性分布式事务解决方案 分布式事务(3)---强一致性分布式事务Atomikos实战 强一致性分布式事务解决方案要求参与事务的各个节点的数据时刻保 ...
- 使用clion阅读eos源码
配置mingw 安装clion 从github克隆源码 使用clion open打开 在cmake上使用boost: sudo apt-get install libboost-all-dev
- ICCV2021 | TOOD:任务对齐的单阶段目标检测
前言 单阶段目标检测通常通过优化目标分类和定位两个子任务来实现,使用具有两个平行分支的头部,这可能会导致两个任务之间的预测出现一定程度的空间错位.本文提出了一种任务对齐的一阶段目标检测(TOOD) ...
- 日常Java(测试 (二柱)修改版)2021/9/22
题目: 一家软件公司程序员二柱的小孩上了小学二年级,老师让家长每天出30道四则运算题目给小学生做. 二柱一下打印出好多份不同的题目,让孩子做了.老师看了作业之后,对二柱赞许有加.别的老师闻讯, 问二柱 ...