- 实习内容:安装并使用pymysql模块编写一个脚本,数据模型自定义,要有表的设计过程,包含基础的增删改查
过程
(1)安装pymysql模块
pip3 install pymysql
(2)创建一个用于创建一张数据表的 .sql 文档
```sql
DROP TABLE IF EXISTS db_Employee;
CREATE TABLE IF NOT EXISTS db_Employee (
Id INT(4) NOT NULL UNIQUE AUTO_INCREMENT PRIMARY KEY COMMENT '用户表Id',
name VARCHAR(30) NOT NULL COMMENT '姓名',
sex INT(1) NOT NULL COMMENT '性别',
address VARCHAR(30) NOT NULL COMMENT '地址',
email VARCHAR(30) NOT NULL COMMENT '邮箱',
Phone INT(10) NOT NULL COMMENT '手机号码',
salary decimal(10) NOT NULL COMMENT '工资',
dept_id INT(1) NOT NULL COMMENT '部门',
create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '最后一次更新时间'
)ENGINE = INNODB default CHARSET = utf8
(3) 编辑一个基于pymysql模块对数据库增删改查的脚本
import pymysql
conn = pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='test01',charset='utf8') #建立连接
cursor = conn.cursor() #使用游标执行sql语句
sql1 = "INSERT INTO db_employee(name,sex,address,email,phone,salary,dept_id) VALUES('John',0,'广东','623@qq.com',13414666666,28000,1)"
effect_row = cursor.execute(sql1) #execute是执行一条
print("插入一条数据,影响行数:",effect_row) #增加一条
sql2 = "INSERT INTO db_employee(name,sex,address,email,phone,salary,dept_id) VALUES(%s,%s,%s,%s,%s,%s,%s)"
effect_row = cursor.executemany(sql2,[('Jetty',0,'英国','333@qq.com',15327530506,9000,1),('Tom',0,'美国','911@qq.com',911-777,8000,1)]) #executemany执行多条语句
print("插入两条数据,影响行数:",effect_row) #批量增加
sql3 = "SELECT * FROM db_employee"
cursor.execute(sql3)
print("查询一条数据为:",cursor.fetchone())
# print("查询所有条数据为:",cursor.fetchall())
# print("查询两条数据为:",cursor.fetchmany(2))
sql4 = "update db_employee set sex = 0,address = '深圳',dept_id = 2 where name = 'jetty' "
effect_row = cursor.execute(sql4)
print("修改一条数据,影响行数",effect_row)
sql5 = "delete from db_employee where name = 'tom' "
effect_row = cursor.execute(sql5)
print("删除一条 name = 'tom'的数据,影响行数",effect_row)
conn.commit() #提交,执行增删改必须要的操作
cursor.close() #关闭游标
conn.close() #关闭连接