1.数据库链接
(22条消息) Pymysql操作_alivefour的博客-CSDN博客
2. 根据用户输入的序号执行不同的功能
# 3. 用户输入目标功能序号
menu_num = int(input('请输入您需要的功能序号:'))
# 4. 根据用户输入的序号执行不同的功能 -- 如果用户输入1,执行添加
if menu_num == 1:
# 添加学员
self.add_student()
elif menu_num == 2:
# 删除学员
self.del_student()
elif menu_num == 3:
# 修改学员信息
self.modify_student()
elif menu_num == 4:
# 查询学员信息
self.search_student()
elif menu_num == 5:
# 显示所有学员信息
self.show_student()
elif menu_num == 6:
# 退出系统 -- 退出循环
break
3.不同的功能
添加学生
# 添加学员
def add_student(self):
# 1. 用户输入姓名、性别、手机号
name = input('请输入您的姓名:')
gender = input('请输入您的性别:')
tel = input('请输入您的手机号:')
#插入信息
sql = " INSERT INTO student (name,gender,tel) VALUE (%s,%s,%s) "
value = (name, gender, tel)
try:
#执行语句
cur.execute(sql, value)
conn.commit()
print('数据插入成功!')
except pymysql.Error as e:
print("数据插入失败:" + e)
conn.rollback()
删除
# 2.3 删除学员
def del_student(self):
# 1. 用户输入目标学员姓名
del_name = input('请输入要删除的学员姓名:')
print(self.student_list)
sql = " delete from student where name= %s "
value = del_name
try:
cur.execute(sql, value)
conn.commit()
print('数据删除成功!')
except pymysql.Error as e:
print("数据删除失败:" + e)
conn.rollback()
修改
i.name = input('姓名:')
i.gender = input('性别:')
i.tel = input('手机号:')
sql = " UPDATE student set gender=%s, tel=%s where name=%s"
value = (i.gender, i.tel, i.name)
try:
cur.execute(sql, value)
conn.commit()
print('数据修改成功!')
except pymysql.Error as e:
print("数据修改失败:" + e)
conn.rollback()
print(f'修改学员信息成功,姓名{i.name}, 性别{i.gender}, 手机号{i.tel}')
查询
# 2.5 查询学员信息
def search_student(self):
# 1. 用户输入目标学员姓名
name = input('请输入您要搜索的学员姓名:')
# SQL插入语句
sql = "select * from student where name=%s"
value=name
try:
# 执行MySQL语句
cur.execute(sql, value)
results = cur.fetchall()
for row in results:
name = row[0]
gender = row[1]
tel = row[2]
print(f'姓名是{name}, 性别是{gender}, 手机号是{tel}')
except pymysql.Error as e:
print("数据查询失败:" + str(e))