#### 练习:
- 建立product表,操作方式operate表
要求
1.定义触发器实现在产品表(product)中每多一个产品,就在操作表(operate)中记录操作方式和时间以及编号记录。
注:操作说明:标记执行delete 、insert、 update
2.定义触发器实现在产品表(product)中每更新一个产品,就在操作表(operate)中记录操作方式和时间以及编号记录。
3.定义触发器实现在产品表(product)中每删除一个产品就,在操作表(operate)中记录操作方式和时间以及编号记录。
```mysql
Product表内容 :
字段名 字段描述 数据类型 主键 外键 非空 唯一 自增
id 产品编号 Int(10) 是 否 是 是 否
name 产品功能 Varchar(20) 否 否 是 否 否
func 主要功能 Varchar(50) 否 否 否 否 否
com 生产厂家 Varchar(20) 否 否 是 否 否
address 家庭住址 Varchar(20) 否 否 否 否 否
operate表内容 :
字段名 字段描述 数据类型 主键 外键 非空 唯一 自增
op_id 编号 Int(10) 是 否 是 是 是
op_type 操作方式 Varchar(20) 否 否 是 否 否
op_time 操作时间 Varchar(20) 否 否 是 否 否
```
- 创建触发器,每次激活触发器后,都会更新operate表
- 创建product_after_insert_trigger
- 创建product_after_update_trigger
- 创建product_after_delete_trigger
- 执行语句向operate表插入操作方法和操作时间
1.创建表
create table product (
id int(10) primary key,
name varchar(20) not null,
func varchar(50),
com varchar(20) not null,
address varchar(20));
create table operate (
op_id int(10) primary key auto_increment,
op_type varchar(20) not null,
op_time varchar(20) not null,
product_id int(10));
2.插入触发器 创建更新触发器
delimiter //
create trigger product_after_insert_trigger
after insert on product
for each row
begin
insert into operate(op_type, op_time, product_id)
values('insert', date_format(now(), '%y-%m-%d %h:%i:%s'), new.id);
end //
delimiter ;
delimiter //
create trigger product_after_update_trigger
after update on product
for each row
begin
insert into operate(op_type, op_time, product_id)
values('update', date_format(now(), '%y-%m-%d %h:%i:%s'), new.id);
end //
delimiter ;
创建删除触发器
delimiter //
create trigger product_after_delete_trigger
after delete on product
for each row
begin
insert into operate(op_type, op_time, product_id)
values('delete', date_format(now(), '%y-%m-%d %h:%i:%s'), old.id);
end //
delimiter ;
测试
insert into product(id, name, com) values(
values(1, 'product1', 'company1'));
update product set name = 'updated_product1' where id = 1;
delete from product where id = 1;
9925

被折叠的 条评论
为什么被折叠?



