🎈 本文持续更新中…
预览版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| create database library; use library; create table book( book_id int auto_increment comment '图书ID', book_name varchar(100) not null default '' comment '图书名称', book_class varchar(10) not null default '' comment '图书分类', primary key (book_id) ) engine=Innodb comment '图书';
desc book;
insert into book(book_name, book_class) values ('高性能 MySQL', '数据库'), ('Python 工匠', '编程语言'), ('机器学习实战', '机器学习'), ('C 语言入门', '编程语言'), ('JAVA编程思想', '编程语言'), ('MySQL 必知必会', '数据库');
select * from book;
|
1 保护表数据不被删除
原本我是想删除一个临时表 book_test 的所有数据,却一部小心写成了 book,结果删除了表数据,后悔莫及(虽然可以恢复,但是很麻烦)。
1
| DELETE FROM library.book;
|
有没有办法保护某些重要的表,不被删除呢?
似乎可以用触发器,在删除之前提示!
1 2 3 4 5 6 7 8 9 10 11
| CREATE TRIGGER book_can_not_delete BEFORE DELETE ON library.book
FOR EACH ROW BEGIN DECLARE msg VARCHAR(255); SET msg='[TRIGGER] Can not delete from library.book'; SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = msg; END;
DELETE FROM library.book;
|
如果你真的有需求删除该表数据时,先删除触发器,再删除数据。
1 2 3
| DROP TRIGGER book_can_not_delete;
DELETE FROM library.book;
|