syntax error from CREATE USER with variables giving username and password

前端 未结 2 2009
滥情空心
滥情空心 2021-01-18 20:13

Stored procedure code:

CREATE DEFINER = `root` @`localhost` PROCEDURE `P_CreateUser3` (
  IN _Username NVARCHAR(30), IN _Password NVARCHAR(32), IN _DBName VA         


        
相关标签:
2条回答
  • 2021-01-18 20:59

    You must use prepared statements because the variables doesn't evaluate directly in queries.

    DELIMITER $$
    
    DROP PROCEDURE IF EXISTS `create_user`$$
    
    CREATE PROCEDURE `create_user`(
        `user_name` VARCHAR(50), 
        `passwd` VARCHAR(255),
        `ip` VARCHAR(50)
    )
    BEGIN
       set @sql = concat("CREATE USER '",`user_name`,"'@'",`ip`,"' IDENTIFIED BY '",`passwd`,"'");
       PREPARE stmt1 FROM @sql;
       EXECUTE stmt1;
       DEALLOCATE PREPARE stmt1;
    
       set @sql = concat("GRANT ALL PRIVILEGES ON * . * TO '",`user_name`,"'@'",`ip`,"' ");
       PREPARE stmt2 FROM @sql;
       EXECUTE stmt2;
       DEALLOCATE PREPARE stmt2;
    
       FLUSH PRIVILEGES;
    END$$
    
    DELIMITER ;
    
    0 讨论(0)
  • 2021-01-18 21:00

    Unfortunately, the use of stored procedure input parameters as passwords in a CREATE USER or GRANT statement is documented in this bug as unsupported. So you cannot actually do what you attempted.

    It would be possible to PREPARE and EXECUTE a statement which is built by CONCAT() to concatenate in the new password, but this is not a secure method and is therefore not recommended. You lose all the security benefits of the stored procedure if you were to do it that way.

    0 讨论(0)
提交回复
热议问题