PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,是一个纯 Python语言 实现的 MySQL 客户端操作库.
下载第三方模块pymsql
下载方式一 cmd 窗口 命令 pip install pymysql
下载方式二 pycharm 下载 文件——————设置————-项目 python解释器
使用python代码操作MySQL数据库
- 数据库连接对象常用的方法
- cursor( ),创建游标
- commit( ),提交事务
- rollback( ),回滚事务
- close(),关闭数据库连接
- 游标对象常用方法
- execute (sql) 执行指定sql
- fetchone() 从查询结果中获取一条记录 返回一维元组(), 没有数据反馈None
- fetchall() 从查询结果中获取所有记录 返回二维元组((),()), 没有数据 返回空元组()
- close() 关闭游标
对数据库基本操作
步骤:
准备SQL语句
- 1. 连接数据库,获取连接对象
- 2. 创建游标对象
- 3. 游标对象执行SQL语句
- 4. 处理执行结果
- 5. 关闭连接
- select_one( sql) 查询1条数据
select_many(sql) 查询多条数据
示例1
#=============需求1增.向学生表添加一个学生信息(sql)============== #=============需求2改:修改编号为2学生信息(sql1)================ #=============需求3删:删除编号为3的学生(sql2)================== #=============需求4查:查询编号为5的学生(sql3)================== import pymysql def student_add(): #1.准备sql语句 sql="insert into student(name,sex,tel) values('小诗','男','12134567835')" print(sql) #2.连接数据库,获取连接对象 db_con=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='schooldb',charset='utf8') print(db_con) #3.创建游标对象 mycur=db_con.cursor() #4.用游标对象执行sql语句 mycur.execute(sql) #5.处理执行结果 db_con.commit() #6.关闭连接 db_con.close() print('学生信息操作已完成') #=============需求2:修改编号为2学生信息================== import pymysql def student_update(): #1.准备sql语句 sql1="update student set name='小余',sex='女',tel='19712345678' where id=2" print(sql1) #2.连接数据库,获取连接对象 db_con=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='schooldb',charset='utf8') print(db_con) #3.创建游标对象 mycur=db_con.cursor() #4.用游标对象执行sql语句 mycur.execute(sql1) #5.处理执行结果 db_con.commit() #6.关闭连接 db_con.close() print('学生信息操作已完成') #=============需求3:修删除编号为3的学生(sql2)================ import pymysql def student_delete(): #1.准备sql语句 sql2="delete from student where id=3" print(sql2) #2.连接数据库,获取连接对象 db_con=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='schooldb',charset='utf8') print(db_con) #3.创建游标对象 mycur=db_con.cursor() #4.用游标对象执行sql语句 mycur.execute(sql2) #5.处理执行结果 db_con.commit() #6.关闭连接 db_con.close() print('学生信息操作已完成') # fetchone() 提取查询结果的一行 返回单个元组() , 没有数据 返回None # fetchall ( ) 提取查询结果的全部行 返回二维元组((),()) 没有数据 返回空元组() #=============需求4查:查询编号为5的学生(sql3)================== import pymysql def student_select(): #1.准备sql语句 sql3="select * from student where id=5" print(sql3) #2.连接数据库,获取连接对象 db_con=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='schooldb',charset='utf8') print(db_con) #3.创建游标对象 mycur=db_con.cursor() #4.用游标对象执行sql语句 mycur.execute(sql3) #5.处理执行结果(游标对象提取查询的结果) data= mycur.fetchone() #6.关闭连接 db_con.close() print(data) #=============需求5查:查询student表中所有的学生(sql4)================== import pymysql def student_select1(): #1.准备sql语句 sql4="select * from student" print(sql4) #2.连接数据库,获取连接对象 db_con=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='schooldb',charset='utf8') print(db_con) #3.创建游标对象 mycur=db_con.cursor() #4.用游标对象执行sql语句 mycur.execute(sql4) #5.处理执行结果(游标对象提取查询的结果) data = mycur.fetchall() #6.关闭连接 db_con.close() print(data) if __name__ == '__main__': #student_add() #student_update() #student_delete() #student_select() student_select1()
示例2
import pymysql def student_add_update_delete(sql): #1.连接数据库,获取连接对象 db_con=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='schooldb',charset='utf8') print(db_con) #2.创建游标对象 mycur=db_con.cursor() #3.用游标对象执行sql语句 mycur.execute(sql) #4.处理执行结果 db_con.commit() #5.关闭连接 db_con.close() print('学生信息操作已完成') #=============需求1增.向学生表添加一个学生信息(sql)============== add_sql="insert into student(name,sex,tel) values('小楠','女','12134566578')" #student_add_update_delete(add_sql) #=============需求2改:修改编号为2学生信息(sql1)================ update_sql="update student set name='小舞',sex='女',tel='13245627834' where id=2" #student_add_update_delete(update_sql) #=============需求3删:删除编号为3的学生(sql2)================== delete_sql="delete from student where id=15" #student_add_update_delete(delete_sql) #=============需求4查:查询编号为5的学生(sql3)================== import pymysql def student_select(): #1.准备sql语句 sql="select * from student where id=5" #1.连接数据库,获取连接对象 db_con=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='schooldb',charset='utf8') print(db_con) #2.创建游标对象 mycur=db_con.cursor() #3.用游标对象执行sql语句 mycur.execute(sql) #4.处理执行结果 student=mycur.fetchone() #查询单行信息返回结果 #mycur.fetchall() 查询表单全部信息,返回结果 #5.关闭连接 db_con.close() print(student) if student==None: print('查询学生不存在') else: print('编号:',student[0]) print('姓名:',student[1]) print('性别:',student[2]) print('电话:',student[3]) #student_select() #=============需求4查:查询编号为5的学生(sql3)================== def select_one(sql): # 1.连接数据库,获取连接对象 db_con = pymysql.connect(host='localhost', port=3306, user='root', password='', database='schooldb',charset='utf8') print(db_con) # 2.创建游标对象 mycur = db_con.cursor() # 3.用游标对象执行sql语句 mycur.execute(sql) # 4.处理执行结果(游标对象提取查询的结果) data = mycur.fetchone() # 5.关闭连接 db_con.close() return data # sql="select * from student where id=1" # student=select_one(sql) # if student == None: # print('查询学生不存在') # else: # print('编号:', student[0]) # print('姓名:', student[1]) # print('性别:', student[2]) # print('电话:', student[3]) #=============需求5查:查询student表中所有的学生(sql4)================== import pymysql def student_select1(): #1.准备sql语句 sql4="select * from student" print(sql4) #2.连接数据库,获取连接对象 db_con=pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='schooldb',charset='utf8') print(db_con) #3.创建游标对象 mycur=db_con.cursor() #4.用游标对象执行sql语句 mycur.execute(sql4) #5.处理执行结果(游标对象提取查询的结果) student = mycur.fetchall() #6.关闭连接 db_con.close() #print(student) for i in range(len(student)): for j in range(len(student[i])): print(student[i][j],end='\t') print() #student_select1() #=============需求5查:查询student表中所有的学生(sql4)================== def select_many(sql1): # 1.连接数据库,获取连接对象 db_con = pymysql.connect(host='localhost', port=3306, user='root', password='', database='schooldb',charset='utf8') print(db_con) # 2.创建游标对象 mycur = db_con.cursor() # 3.用游标对象执行sql语句 mycur.execute(sql1) # 4.处理执行结果(游标对象提取查询的结果) data = mycur.fetchall() # 5.关闭连接 db_con.close() return data sql1="select id,name,sex from student where name like '王%'" student=select_many(sql1) if student==(): print('查询信息不存在') else: for i in range(len(student)): for j in range(len(student[i])): print(student[i][j], end='\t') print()
示例3
# 学生信息管理 import pymysql # 查询表单中全部的信息 def select_many(sql): # 1.连接数据库,获取连接对象 db_con = pymysql.connect(host='localhost', port=3306, user='root', password='', database='schooldb', charset='utf8') # 2.创建游标对象 mycur = db_con.cursor() # 3.用游标对象执行sql语句 mycur.execute(sql) # 4.处理执行结果(游标对象提取查询的结果) data = mycur.fetchall() # 5.关闭连接 db_con.close() return data # 查询表单中单行信息 def select_one(sql): # 1.连接数据库,获取连接对象 db_con = pymysql.connect(host='localhost', port=3306, user='root', password='', database='schooldb', charset='utf8') # 2.创建游标对象 mycur = db_con.cursor() # 3.用游标对象执行sql语句 mycur.execute(sql) # 4.处理执行结果(游标对象提取查询的结果) data = mycur.fetchone() # 5.关闭连接 db_con.close() return data # 进行表单的增加,修改和删除 def student_add_update_delete(sql): # 1.连接数据库,获取连接对象 db_con = pymysql.connect(host='localhost', port=3306, user='root', password='', database='schooldb', charset='utf8') # 2.创建游标对象 mycur = db_con.cursor() # 3.用游标对象执行sql语句 mycur.execute(sql) # 4.处理执行结果 db_con.commit() # 5.关闭连接 db_con.close()
import pymysql import mytools from mytools import select_many,select_one,student_add_update_delete class Stu(): def all_student(self): print('全部学生信息'.center(65, '=')) sql = "select * from student" student = select_many(sql) for i in range(len(student)): for j in range(len(student[i])): print(student[i][j], end='\t') print() def add_student(self): print('添加学生信息'.center(65, '=')) name = input('请输入学生名字:') sql = f"select * from student where name='{name}'" stu = select_one(sql) if stu is None: sex = input('请输入学生性别:') tel = input('请输入学生电话:') sql = f"insert into student(name,sex,tel) values('{name}','{sex}','{tel}')" student_add_update_delete(sql) print('学生信息添加成功') else: print('学生已存在,请勿重新添加') def change_student(self): print('修改学生信息'.center(65, '=')) id = int(input('输入学生的编号:')) name = input('输入学生姓名:') sex = input('输入学生的性别:') tel = input('输入学生的电话:') sql = f"update student set name='{name}',sex='{sex}',tel='{tel}' where id={id}" student_add_update_delete(sql) print('学生信息修改成功') def delete_student(self): print('删除学生信息'.center(65, '=')) id = int(input('输入学生的编号:')) sql = f"delete from student where id={id}" student_add_update_delete(sql) print('学生信息删除成功') def find_student(self): while True: print('查找学生信息'.center(65, '-')) print(f'a.编号查找\tb.姓名查找\tc.性别查找\td.电话查找') num = input('请选择查找方式:') if num == 'a': print('编号查找'.center(65, '-')) id = int(input('输入学生的编号:')) sql = f"select * from student where id={id}" student = select_one(sql) print(student) elif num == 'b': print('姓名查找'.center(65, '-')) name = input('输入学生姓名:') sql = f"select * from student where name='{name}'" student = select_one(sql) print(student) elif num == 'c': print('性别查找'.center(65, '-')) sex = input('输入学生性别:') sql = f"select * from student where sex='{sex}'" student = select_many(sql) print(student) elif num == 'd': print('电话查找'.center(65, '-')) tel = input('输入学生电话:') sql = f"select * from student where tel='{tel}'" student = select_one(sql) for i in range(len(student)): for j in range(len(student[i])): print(student[i][j], end='\t') print() break else: print('输入无效,请重新选择') cla=Stu() while True: print('学生信息管理'.center(65,'=')) print(f'1.全部学生\t2.添加学生\t3.修改学生\t4.删除学生\t5.查找学生\t0.退出系统') num=input('请选择菜单编号:') if num=='1': cla.all_student() elif num=='2': cla.add_student() elif num=='3': cla.change_student() elif num=='4': cla.delete_student() elif num=='5': cla.find_student() elif num=='0': print('退出系统'.center(65, '=')) print('退出系统') break else: print('输入无效,请重新选择')