没有比人更高的山

MySQL中drop user if exists功能的实现方法

在编写可以重复执行的创建数据库的脚本时,我们知道下面语句可以测试数据库是否存在,如果存在的话就删除掉

1
DROP DATABASE IF EXISTS testdb;

但是我们没办法测试用户是否存在,MySQL是没有drop user if exist这样的功能的。详见:http://bugs.mysql.com/bug.php?id=19166

不过有另外一种变通的办法可以实现同样的功能,代码如下:

1
2
3
4
# a way to implement the functionality of 'drop user if exists' which mysql does
# not support for now
GRANT usage ON *.* TO testdb IDENTIFIED BY 'testdb';
DROP user testdb;

在执行grant的时候,如果数据库中不存在这个用户,那么MySQL会创建一个用户,并且赋以usage权限,usage权限等同于“no privileges”,至于为什么会有这个特殊的权限请见http://dev.mysql.com/doc/refman/5.0/en/privileges-provided.html#priv_usage,主要是在修改已有用户的grant option时使用的。

另外,使用MySQL5.0.0时,执行drop user时并不会删除其权限。MySQL5.0.2已经修正了这个问题,删除用户的时候会一并连权限以前删除。详见:http://dev.mysql.com/doc/refman/5.0/en/drop-user.html

VN:F [1.7.5_995]
Rating: 0.0/10 (0 votes cast)
VN:F [1.7.5_995]
Rating: -1 (from 1 vote)

No Comments yet »

发表评论:

Switch to our mobile site