在贴代码之前先说明一下python连接mysql数据库的步骤
1.首先导入pymysql包,如果没有,则在左上角File->Settings->找到project->project Interpreter 点击右上角加号,搜索pymysql,选中pymysql点击坐下角Install Package,等待安装完毕即可
2.然后就是代码部分,下面贴一个简单做查询的代码
import pymysql
def query():
connection = pymysql.connect(host="localhost", user="root",
password="123456", database="student",
port=3306)
# 获取游标 对数据库进行操作 设置返回的每条记录都是一个字典,返回的结果集是一个列表
cur = connection.cursor(cursor=pymysql.cursors.DictCursor)
# 写sql语句
sql = "select * from stu"
try:
cur.execute(sql)
students = cur.fetchall()
print(type(students))
print(students)
except Exception as e:
raise e
finally:
connection.close() # 关闭连接
query()
运行结果为:
<class 'list'>
[{'id': '123', 'name': '张三', 'sex': '男', 'phone': '123456789'}]
如果不将游标设置 ,则返回的都是元组类型的,可以看如下代码:
import pymysql
def query():
connection = pymysql.connect(host="localhost", user="root",
password="123456", database="student",
port=3306)
# 获取游标 对数据库进行操作 设置返回的每条记录都是一个字典,返回的结果集是一个列表
# cur = connection.cursor(cursor=pymysql.cursors.DictCursor)
cur = connection.cursor()
# 写sql语句
sql = "select * from stu"
try:
cur.execute(sql)
students = cur.fetchall()
print(type(students))
print(students)
except Exception as e:
raise e
finally:
connection.close() # 关闭连接
query()
运行结果为:
<class 'tuple'>
(('123', '张三', '男', '123456789'),)
这就是一个简单的查询,我们设置游标将返回的记录设置为字典类型,结果集为列表,与我们之前存储的一样,字典更便于操作
后面的插入删除看具体代码,基本连接mysql就是这样子。
------------------------------------------------------------------分割线------------------------------------------------------------------
下面是这个学生管理系统具体代码,里面注释很详细,只不过是在我之前的学生管理系统上加了数据库操作
之前的管理系统https://blog.csdn.net/hsunnyc/article/details/89097679
import pymysql
name_list = [] # 存储学生信息字典,学生信息用字典存,再用列表存储字典
# 菜单
def display_menu():
print("-" * 30)
print(" 学生管理系统 v8.8 ")
print("1.添加学生信息")
print("2.删除学生信息")
print("3.修改学生信息")
print("4.查询单个学生信息")
print("5.查询所有学生信息")
print("6.退出系统")
print("-" * 30)
# 选择序号的获得
def get_choice():
selected_key = input("请输入选择的序号:")
return selected_key
# 检查性别是否合法
def check_sex(new_sex):
flag = True
while flag:
if new_sex == '男' or new_sex == '女':
flag = False
else:
new_sex = input("输入性别有误,请重新输入(男/女):")
return new_sex
# 检查电话号码是否合法
def check_phone(new_phone):
flag = True
while flag:
if new_phone.isdigit():
flag = False
else:
new_phone = input("您输入的电话号码有误,请重新输入:")
return new_phone
# 检查学号是否重复或者有误
def check_id(new_id):
flag = True
while flag:
# 先检查是不是纯数字再去考虑是否重复的事情,如果不是纯数字直接pass
if new_id.isdigit():
for i in range(len(name_list)):
if name_list[i]['id'] == new_id:
new_id = check_id(input("您输入的学号重复,请重新输入:"))
flag = False
else:
new_id = input("您输入的学号有误,请重新输入:")
return new_id
# 添加学生信息 返回学生信息字典
def add_name():
new_info = {}
new_id = check_id(input("请输入学号:"))
new_info['id'] = new_id
new_name = input("请输入姓名:")
new_info['name'] = new_name
new_sex = check_sex(input("请输入性别(男/女):"))
new_info['sex'] = new_sex
new_phone = check_phone(input("请输入电话号码:"))
new_info['phone'] = new_phone
name_list.append(new_info)
# 将新学生信息添加到数据库中
stu_insert(new_info)
print("添加成功!")
# 查询所有学生信息 --是从数据库中查询信息的
def find_all():
print("=" * 30)
global name_list
name_list = query()
for name in name_list:
print(name['id'], name['name'], name['sex'], name['phone'])
print("=" * 30)
# 删除学生信息
def del_name():
del_id_is = input("请输入要删除的学生学号:")
flag = False
index = 0
for i in range(len(name_list)):
if name_list[i]['id'] == del_id_is:
flag = True
index = i
break
if flag:
name_list.pop(index)
stu_delete(del_id_is)
print("删除成功!")
else:
print("学生未找到!请检查学号输入是否有误!")
# 名字修改细节函数
def choice_of_name(index):
while True:
choice = input("请输入要修改学生的(1.姓名 2.性别 3.电话号码,4.全部修改):")
if choice == '4':
"""
要做到内存中的数据与数据库中数据同时修改的话,我做的是先修改本地的数据,
再对数据库中的数据做修改
"""
new_name = input("请输入新的姓名:")
name_list[index]['name'] = new_name
new_sex = check_sex(input("请输入性别(男/女):"))
name_list[index]['sex'] = new_sex
new_phone = check_phone(input("请输入电话号码:"))
name_list[index]['phone'] = new_phone
stu_modify(name_list[index])
break
elif choice == '1':
new_name = input("请输入新的姓名:")
name_list[index]['name'] = new_name
stu_modify(name_list[index])
break
elif choice == '2':
new_sex = check_sex(input("请输入性别(男/女):"))
name_list[index]['sex'] = new_sex
stu_modify(name_list[index])
break
elif choice == '3':
new_phone = check_phone(input("请输入电话号码:"))
name_list[index]['phone'] = new_phone
stu_modify(name_list[index])
break
else:
print("输入有误,请重新输入!")
# 修改学生信息
def re_name():
id_is = input("请输入要修改的学生学号:")
flag = False
index = 0
# 先找到要修改的学生的下标
for i in range(len(name_list)):
if name_list[i]['id'] == id_is:
flag = True
index = i
break
if flag:
choice_of_name(index)
print("修改成功!")
else:
print("修改失败,学生信息未找到!")
# 查询单个学生信息 --并不是从数据库中查询的,还是从内存中查询的
def find_name():
find_id_is = input("请输入要查询的学生学号:")
flag = False
index = 0
for i in range(len(name_list)):
if name_list[i]['id'] == find_id_is:
flag = True
index = i
break
if flag:
print("学生查询到,学生信息为:")
print(name_list[index]['id'], name_list[index]['name'], name_list[index]['sex'], name_list[index]['phone'])
else:
print("学生未找到!")
# 获取数据库连接的方法
def get_connection():
connection = pymysql.connect(host="localhost", user="root", password="123456", database="student", port=3306)
return connection
# 初始化的时候从数据库中查询学生信息
def query():
connection = get_connection()
# 获取游标 对数据库进行操作 并且将返回值设置为字典类型
cur = connection.cursor(cursor=pymysql.cursors.DictCursor)
# 写sql语句
sql = "select * from stu"
try:
cur.execute(sql)
students = cur.fetchall()
"""
此处判断很重要,如果数据库中没有记录,则会结果是一个空的元组类型,
如果有记录,则结果是list类型,所以可以根据类型来判断数据库是否为空,
如果不是就返回一个空列表。
"""
if type(students) == list:
return students
else:
return []
except Exception as e:
raise e
finally:
connection.close() # 关闭连接
# 初始化函数,从数据库中查询到的赋值给name_list
def name_init():
try:
global name_list
name_list = query()
print("成功获取数据库中数据!")
except Exception as e:
raise e
# 添加学生 -- 直接添加到数据库里面
def stu_insert(stu):
connection = get_connection()
# 获取游标 对数据库进行操作 并且将返回值设置为字典类型
cur = connection.cursor(cursor=pymysql.cursors.DictCursor)
# 写sql语句
sql = "insert into stu(id,name,sex,phone) values('%s','%s','%s','%s')"
sid = stu['id']
name = stu['name']
sex = stu['sex']
phone = stu['phone']
try:
cur.execute(sql % (sid, name, sex, phone))
connection.commit()
except Exception as e:
# 错误回滚
connection.rollback()
raise e
finally:
connection.close() # 关闭连接
# 删除学生 --直接从数据库里面删除
def stu_delete(sid):
connection = get_connection()
cur = connection.cursor()
sql = "delete from stu where id = '%s'"
try:
cur.execute(sql % sid)
connection.commit()
except Exception as e:
# 错误回滚
connection.rollback()
raise e
finally:
connection.close() # 关闭连接
# 修改学生信息
def stu_modify(stu):
connection = get_connection()
cur = connection.cursor()
sid = stu['id']
name = stu['name']
sex = stu['sex']
phone = stu['phone']
sql = "update stu set name='%s',sex='%s',phone='%s' where id='%s'"
try:
cur.execute(sql % (name, sex, phone, sid))
connection.commit()
except Exception as e:
# 错误回滚
connection.rollback()
raise e
finally:
connection.close() # 关闭连接
def main():
name_init()
exit_name = True
while exit_name:
display_menu()
key = get_choice()
if key == '1':
add_name()
elif key == '2':
del_name()
elif key == '3':
re_name()
elif key == '4':
find_name()
elif key == '5':
find_all()
elif key == '6':
exit_name = False
else:
print("请输入正确的数值!")
main()
数据库表结构:
注意下面的每个字段的字符集,都是utf8。