Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an environment variable in the MySQL console

Tags:

mysql

I can connect to the console as root using an environment variable:

mysql -u root -p${MYSQL_ROOT_PASSWORD}

I’d like to be able to use a different environment variable in a statement

CREATE USER ${MYSQL_USER} IDENTIFIED BY ${MYSQL_USER_PASSWORD};

Which obviously doesn’t work (or why would I be asking). Is there any way I can use an environment variable in the console?

like image 285
WhiskerBiscuit Avatar asked May 17 '19 16:05

WhiskerBiscuit


People also ask

How do I set environment variables in MySQL?

On the Windows desktop, right-click the My Computer icon, and select Properties. Next select the Advanced tab from the System Properties menu that appears, and click the Environment Variables button. Under System Variables, select Path, and then click the Edit button. The Edit System Variable dialogue should appear.

How do I use variables in MySQL?

MySQL variable assignment There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.

How do I see MySQL environment variables?

SHOW VARIABLES; If you want to see only a specific variable, you can use this command. Obviously you'd want to replace the max_connect_errors in that command with the variable that you're looking for. SHOW VARIABLES LIKE '%max_connect_errors%';

How do I run an environment variable?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.


1 Answers

I don't think there's any way to access environment variables from MySQL queries. But you can construct the MySQL query and substitute variables in the shell.

mysql -e "CREATE USER '{$MYSQL_USER}' IDENTIFIED BY '${MYSQL_USER_PASSWORD}'"

The shell will substitute the variables into the string before it's passed to the mysql command. For longer queries you can use a here-doc:

mysql <<EOF
CREATE USER '{$MYSQL_USER}' 
IDENTIFIED BY '${MYSQL_USER_PASSWORD}'
EOF
like image 164
Barmar Avatar answered Oct 23 '22 04:10

Barmar