python实现对数据库增删改查

一、#导入MySQLdb
import MySQLdb
二、#建立数据库连接
conn = MySQLdb.connect(“localhost”,“root”,“123456”,“duck”, charset=‘utf8’)
三、 #建立游标时,加上"MySQLdb.cursors.DictCursor",让数据查询结果返回字典类型
cur = conn.cursor(MySQLdb.cursors.DictCursor)
四、#新增
def addUser(xuehao,name,math,english,chinese):
user=(xuehao,name,math,english,chinese)
#sql语句
sql = “insert into Student_Score ( xuehao,name,math,english,chinese) values(%s,%s,%s,%s,%s)”
#执行语句
cur.execute(sql,user)
#提交sql
conn.commit()
#关闭数据库连接
conn.close
五、#修改
def update(xuehao,name,math,english,chinese):
key=(xuehao,name,math,english,chinese,xuehao)
#sql语句
sql=“update Student_Score set xuehao=%s , name=%s, math= %s , english= %s,chinese= %s where xuehao=%s”
cur.execute(sql,key)
#提交sql
conn.commit()
#关闭数据库连接
conn.close
六、#删除
def delete_table(xuehao,):
key=(xuehao,)
#sql语句
sql=“delete from Student_Score where xuehao=%s”
cur.execute(sql,key)
#提交sql
conn.commit()
#关闭数据库连接
conn.close
def selectUser(xuehao):
key=(xuehao,)
#sql语句
sql = “select * from Student_Score where xuehao=%s”
#执行语句
cur.execute(sql,key)
result = cur.fetchall()
#提交sql
print(list(result))
Student=list(result)

#关闭数据库连接
conn.close
return Student

if name==“main”:
#addUser(‘202302001’,‘张三’,‘100’,‘100’,‘100’)
#update(‘20230220’,‘张小三’,‘108’,‘100’,‘100’)
#delete_table(‘20230220’,)

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值