如何将GRANT与变量一起使用?

时间:2013-02-12 10:35:57

标签: mysql grant

我在MySql中遇到了GRANT和变量的麻烦。

SET @username := 'user123', @pass := 'pass123';

GRANT USAGE ON *.* TO @username@'%' IDENTIFIED BY @pass;
GRANT INSERT (header1, header2, headern) ON `data` TO @username@'%';
GRANT SELECT (header1, header2) ON `data2` TO @username@'%';

我想在脚本开头将用户名和密码放入变量中,然后在GRANT中使用它们

所以不要这样:

GRANT USAGE ON *.* TO 'user123'@'%' IDENTIFIED BY 'pass123';

我想使用这样的东西:

GRANT USAGE ON *.* TO @username@'%' IDENTIFIED BY pass;

如果有人能告诉我正确的陈述,我真的很感激。 谢谢你的到来!

1 个答案:

答案 0 :(得分:5)

SET @object = '*.*';
SET @user = '''user1''@''localhost''';

SET @query = CONCAT('GRANT UPDATE ON ', @object, ' TO ', @user);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

DROP PROCEDURE IF EXISTS `test`.`spTest`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `spTest`( varLogin char(16), varPassword char(64) )
BEGIN
    DECLARE varPasswordHashed CHAR(41);
    SELECT PASSWORD(varPassword) INTO varPasswordHashed;

    # Any of the following 3 lines will cause the creation to fail
    CREATE USER varLogin@'localhost' IDENTIFIED BY varPassword;
    GRANT USAGE ON test.* TO varLogin@'localhost' IDENTIFIED BY varPassword;
    GRANT USAGE ON test.* TO varLogin@'localhost' IDENTIFIED BY PASSWORD varPasswordHashed;

    ## The following 3 lines won't cause any problem at create time
    CREATE USER varLogin@'localhost' IDENTIFIED BY 'AnyPassordString';
    GRANT USAGE ON test.* TO varLogin@'localhost' IDENTIFIED BY 'AnyPassordString';
    GRANT USAGE ON test.* TO varLogin@'localhost' IDENTIFIED BY PASSWORD  'AnyPassordString';  
END$$

DELIMITER;