【转】MySQL中GRANT权限的时候特殊字符转义

碰到grant的问题,发现这篇文章,做个转载:

 

原文地址:http://blog.useasp.net/archive/2013/05/21/MySQL-special-character-escape-method-when-grant-privilages-to-user.aspx

 

MySQL中使用了下划线的数据库名,今天在GRANT的时候,死活无法为用户赋予权限,一直报错。查看了官方的文档,文档中说:如果使用下划线的数据库在使用GRANT的时候,需要对数据库的下划线进行转义

  官方文档的全文如下:

1
2
3
4
5
6
7
8
The “_” and “%” wildcards are permitted when specifying
database names in GRANT statements that grant privileges at
the global or database levels. This means, for example, that
if you want to use a “_” character as part of a database name,
you should specify it as “\_” in the GRANT statement, to
prevent the user from being able to access additional
databases matching the wildcard pattern; for example,
GRANT ... ON `foo\_bar`.* TO ....

GRANT语句用于在全局层级或数据库层级赋予权限。当在GRANT语句中指定数据库名称时,允许使用‘_’和‘%’通配符。这意味着,如果您想要使用‘_’字符作为一个数据库名称的一部分,您应该在GRANT语句中指定它为‘\_’,以防止用户可以访问其它符合此通配符格式的数据库;例如,GRANT ... ON `foo\_bar`.* TO ...。

  说明非常明确,就是在碰到下划线和百分号的时候,为了防止GRANT的时候权限漂移,需要明确的对这两个通配符进行转义,转义符为\,因此有了如下的语句:

1
GRANT ALL ON 'db\_test' .*  TO 'test_user' ;

 恩,看上去是如此的完美,但,非常遗憾的是,MySQL接受到这个语句直接报错:


1
2
ERROR 1064 (42000): You have an error  in your SQL syntax;  check the manual that
corresponds  to your MySQL server version  for the  right syntax  to use near  '' db\_test '.* TO ' test_user '' at line 1

经过多次测试,终于发现这个语法应该变成:

1
GRANT ALL ON `db\_test`.*  TO 'test_user' ;

发现不同了吗?至少我当时没有发现,经过尝试才发现,转义的时候,不仅原有的通配符需要反斜杆[\]进行转义,就连包含转义字串的引号也要变成反勾号!反勾号是啥?就是标准键盘中主键盘数字键1前面的那个键(也就是ESC下面的那个键)。

扫描二维码关注公众号,回复: 1201095 查看本文章

  经过修正后的SQL语句非常顺利的执行了,类似的情况,在GRANT中需要注意的是TO后面的User,平时User字串是可以不用单引号的,但如果User字串中包含了中划线(-)的时候,或者含有通配符(%)的时候,则必须要有引号包含。

 

,jdbc的url 中同样需要转义:

url=jdbc:mysql://127.0.0.1:3306/db\_dev?useUnicode=true&characterEncoding=utf-8

猜你喜欢

转载自hejianhuacn.iteye.com/blog/2081380