学生管理系统-python操作数据库参考

该文展示了如何使用Python的pymysql库进行数据库的基本操作,包括建立连接、设置游标、插入数据、查询数据、更新记录以及删除记录。
摘要由CSDN通过智能技术生成
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()  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值