16

I'd like to do this:

#Variables
SET @username="jdoe", @password="secret";

# Insert a new MySQL User
CREATE USER @username@'localhost' IDENTIFIED BY @password;GRANT USAGE ON *.* TO @username@'localhost' IDENTIFIED BY @password WITH MAX_QUERIES_PER_HOUR 120 MAX_CONNECTIONS_PER_HOUR 60 MAX_UPDATES_PER_HOUR 60 MAX_USER_CONNECTIONS 2;

But get:

#1064 - 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 '@username@'localhost' IDENTIFIED BY @password' at line 2

How do I use a variable in the CREATE USER statement?

2

1 Answer 1

18

You can use dynamic SQL as:

SET @query1 = CONCAT('
        CREATE USER "',@username,'"@"localhost" IDENTIFIED BY "',@password,'" '
        );
PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @query1 = CONCAT('
    GRANT USAGE ON *.* TO "',@username,'"@"localhost" IDENTIFIED BY "',@password,'" WITH
          MAX_QUERIES_PER_HOUR 120 MAX_CONNECTIONS_PER_HOUR 60 MAX_UPDATES_PER_HOUR 60 
          MAX_USER_CONNECTIONS 2'
        );
PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;
Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't seem to be working... I get #1064 - 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 'secret; GRANT USAGE ON *.* TO jdoe@'localhost' IDENTIFIED BY secret ' at line 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.