How to use GRANT with variables?

喜欢而已 提交于 2019-12-23 16:34:34

问题


I have some troubles with GRANT and variables together in MySql.

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@'%';

I'd like to put username and password into variables at the begining of the script and then later use them in GRANT

So instead of this:

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

I'd like to use something like this:

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

I'd really appreciate, if someone could show me the proper statements. Thank you in advence!


回答1:


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;


来源:https://stackoverflow.com/questions/14830493/how-to-use-grant-with-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!