问题:
练习:MySQL数据库编程
题目描述:创建一个测试数据库test.db,该数据库中包含一张teacher表,该数据表含有六个字段教工号tid、姓名tname、性别tsex、年龄tage、职称ttitle。
提示:
- 在网址MySQL :: Download MySQL Community Server上下载mysql数据库压缩文件mysql-8.0.28-winx64.zip(或者老师直接提供)。解压该压缩文件,并修改目录为mysql8,内含有bin和data目录,将mysql8目录复制到目录D:\mysql。
- 以管理员身份打开cmd,进入D:\mysql\mysql8\bin,创建db数据库,创建teacher数据表,输入数据记录如图5-1所示。(操作参见数据库ppt)
图5-1
(3)以此数据库为基础,编写Python代码分别完成数据添加、删除、修改和查询操作。
通过SQL语句insert、delete、update、select分别实现对应数据操作功能。Python操作MySQL数据库程序代码的测试结果如下图5-2所示。
第一步——Mysql操作:
mysql> use test
Database changed//创建表格
mysql> create table teacher(
-> tid char(7) not null,//not null 表示tid的值不能为空
-> tname varchar(50) not null,
-> tsex char(2) not null,
-> tage int not null,
-> ttitle varchar(50) not null,
-> primary key (tid)
-> )engine=innoDB default charset=utf8;
Query OK, 0 rows affected (0.01 sec)//查询表格的结构
mysql> insert into teacher values('2021001','张珊','女',32,'讲师');//插入数据
Query OK, 1 row affected (0.00 sec)第二步——Python环境操作MySQL数据库:
import pymysql dp=pymysql.connect(host='localhost',user='root',password='117503',database='test')#连接数据库 cur=dp.cursor()#创建游标对象cur #查询 cur.execute("select * from teacher")#游标对象执行SQL语句,将Python操作端和MySQL数据库联系起来 results1 = cur.fetchall()#通过游标对象的fetchall()方法获取游标中的所有数据(这里是一个元组) print(results1)#输出获得的数据 #增加一行 sql = "insert into teacher values ('%s','%s','%s',%s,'%s')" % ("2001024","王立军","男",32,"讲师") cur.execute(sql) dp.commit() cur.execute("select * from teacher") results2=cur.fetchall() print(results2) #删除一行 sql="delete from teacher where tid='2001024';" cur.execute(sql) dp.commit() cur.execute("select * from teacher") results3=cur.fetchall() print(results3) #修改一行的数据 sql="update teacher set tname='张san',ttitle='副教授' where tid='2021001';" cur.execute(sql) dp.commit() cur.execute("select * from teacher") results4=cur.fetchall() print(results4) dp.close()
注释:Python环境下,先要导入pymysql模块(我用的pycharm,可以直接搜索pymysql并导入),然后连接数据库就行了,注意,Python端对表格的操作和MySQL服务器里操作表格的格式大致相同,注意,Python端修改、删除、增加表格数据都要有dp.commit(),输出结果如问题图二所示
Python 作业4+实验三
最新推荐文章于 2024-07-11 20:24:07 发布