教程集 www.jiaochengji.com
教程集 >  数据库  >  mysql  >  正文 防止mysql表被清空的方法详解

防止mysql表被清空的方法详解

发布时间:2016-05-12   编辑:jiaochengji.com
本文介绍了为防止mysql表被清空所用到的一些方法,mysql清空表的有效阻止方法,有需要的朋友参考下。

为阻止用户删除或清空表以及数据,可以直接从权限下手,给他少量的权限即可。
比如,防止用户进行truncate 操作, 可以给如下权限:
 

复制代码 代码示例:
t_girl=# create role ytt3 with login connection limit 1 password 'ytt3';
create role
t_girl=# alter schema ytt owner to ytt3;
alter schema
t_girl=# grant select on all tables in schema ytt to ytt3;
grant

现在用新用户ytt3登陆并且执行truncate,发现被禁止。
 

复制代码 代码示例:
bash-4.1$ psql -u ytt3 t_girl
psql (9.3.4)
type "help" for help.
t_girl=> truncate table j2;
error: permission denied for relation j2

当测试时,一般来说,管理员为了方便懒得去分配各种各样细的权限。
那么,在创建表时,就得给这张表来做对应的限制。
当然了,生产环境不建议这么做。

创建一个基于语句的触发器就可以:
 

复制代码 代码示例:

t_girl=# \sf prevent_truncate
create or replace function public.prevent_truncate()
 returns trigger
 language plpgsql
as $functio$
begin
raise exception 'prevent "%" to be truncated!', tg_table_schema||tg_table_name;
return new;
end;
$function$

t_girl=# \d j2
        table "ytt.j2"
 column | type | modifiers
--------+---------+-----------
 id | integer |
 str2 | text |
triggers:
    trigger_truncate_before before truncate on j2 for each statement execute procedure ytt.prevent_truncate()

t_girl=#

t_girl=# truncate table j2;
error: prevent "ytt.j2" to be truncated!

这种方法也只是对于提供了这项功能的数据库才ok。 比如mysql的触发器只提供了基于行的操作,那么语句的操作就不能触发了。
所以,如果在mysql上来实现这点,就比较麻烦。
要么,就从权限入手,
 

复制代码 代码示例:
mysql> truncate table j2;
error 1142 (42000): drop command denied to user 'ytt3'@'localhost' for table 'j2'

要么,就对数据库的操作用sproc封装起来,
 

复制代码 代码示例:
+------------------------------------+
| error |
+------------------------------------+
| prevent t_girl.j2 to be truncated! |
+------------------------------------+
1 row in set (0.00 sec)

您可能感兴趣的文章:
防止mysql表被清空的方法详解
MySQL常见错误代码解析
mysql LOCK TABLES和UNLOCK TABLES
php中防止ddos恶意攻击的方法参考
MySQL临时表的简单用法详解
mysql完全卸载步骤分享
CentOS 6.2 RPM安装MySQL5.0.16的方法介绍
js防止表单重复提交、刷新、后退的方法介绍
分享:mysql常用命令
安装连接mysql的工具Navicat 出现1044/1045错误的解决方法

关键词: mysql清空表   
[关闭]
~ ~