4

我在 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;

如果有人可以向我展示正确的陈述,我将不胜感激。提前谢谢你!

4

1 回答 1

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;
于 2013-02-12T10:56:16.853 回答