import pymysql
# 数据库设置
db_config = {
'user': 'user',
'password': 'password',
'db': 'py21', # 数据库名
'charset': 'utf8', # 注意不要有-哦
}
conn = pymysql.connect(**db_config)
# 1.创建游标:
cur = conn.cursor()
# 增
try:
# 执行sql语句
cur.execute('insert into student values("李明","男","112233")')
# 提交数据
conn.commit()
except Exception as e:
print(e)
# 如果发生错误,回滚
conn.rollback()
# 查
cur.execute("select * from student")
row = cur.fetchone()
while row:
print(row)
row = cur.fetchone()
# 改
cur.execute(f'select * from student where phone="{inputPhone}"') # 先查,电话唯一
if cur.fetchone(): # 有,修改
inputName = textName.get()
inputSex = textSex.get()
try:
cur.execute(f'update student set name="{inputName}",phone="{inputPhone}",sex="{inputSex}" where phone="{inputPhone}"')
result.set("修改成功")
except Exception as e:
# 如果发生错误,回滚
print(f"发生错误:{e}")
else:
print("没有信息,无法修改")
# 删
try:
res = cur.execute(f'delete from student where name="{enterName}"')
if res: # res,删除操作影响的行数。0为没有删除任何一条数据
print("删除成功")
else:
# result.set("学生不存在")
print("学生不存在")
conn.commit()
except Exception as e:
# 如果发生错误,回滚
print(f"发生错误:{e}")
conn.rollback()
学生管理系统-python操作数据库参考
于 2023-05-11 14:18:58 首次发布
该文展示了如何使用Python的pymysql库进行数据库的基本操作,包括建立连接、设置游标、插入数据、查询数据、更新记录以及删除记录。
摘要由CSDN通过智能技术生成