简单的数据库操作

import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='Helloguitar532123', charset='utf8')
# 获得游标
cursor = conn.cursor()
# 创建数据库
db_student = 'create database if not exists db_stu_info2'
cursor.execute(db_student)
# 创建数据表
sql_use = 'use db_stu_info2'
cursor.execute(sql_use)
sql_table = 'create table if not exists students(stuID int primary key ,'\
    'stuName varchar(20),stuGender varchar(20),stuAge int)'
cursor.execute(sql_table)
# 插入数据
sql_one = "insert into students (stuID, stuName, stuGender, stuAge) values (%d,'%s','%s',%d)"
data1 = (1,'张三','女',20)
data2 = (2,'李四','男',22)
data3 = (3,'王五','女',20)
data4 = (4,'赵六','男',19)
data5 = (5,'孙七','女',22)
for i in [data1,data2,data3,data4,data5]:
    cursor.execute(sql_one % i)
conn.commit()
# 修改数据
sql = "update students set stuAge = '%d' where stuID = %d"
data = (21,5)
cursor.execute(sql % data)
conn.commit()
# 查询数据
sql = "select stuID,stuName from students where stuGender = '女'"
cursor.execute(sql)
for row in cursor.fetchall():
    print("学号: %d 姓名: '%s'" % row)
# 删除数据
sql = 'delete from students where stuID = %d limit %d'
data = (5,1)
cursor.execute(sql % data)
conn.commit()
print('共删除%d条数据' % cursor.rowcount)
cursor.close()  # 关闭游标
conn.close()  # 关闭连接



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值