Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass MySQL variables to script from command line

I have a MySQL update script I'd like to run from the command line, but I want to be able to pass a stage domain variable to the script.

I know this won't work, but it's the best way I can describe what I'm trying to do:

$ -uroot -hlocalhost mydatabase  --execute "SET @domain = 'mydomain.dev' " < ./sql/update_domain.sql

Inside the script, I'm using the @domain variable, to update some configuration variables in a config table, using commands like this:

UPDATE my_cfg SET value = @domain WHERE name = 'DOMAIN';

Basically I want to prefix the SET @domain on the update_domain.sql file.

Any ideas how I can rectify my approach?

like image 389
josef.van.niekerk Avatar asked Nov 22 '13 12:11

josef.van.niekerk


People also ask

How do I pass a variable to a MySQL script?

First Step: Use of Set command. SET @anyVariableName − = 'yourValue'; Second Step: Pass a variable to a MySQL script. Display all records from the table using select statement.

How do I run a MySQL script from the command line?

use the MySQL command line client: mysql -h hostname -u user database < path/to/test. sql. Install the MySQL GUI tools and open your SQL file, then execute it. Use phpmysql if the database is available via your webserver.

How do I run a MySQL script from the command line in Windows?

Enter mysql.exe -uroot -p , and MySQL will launch using the root user. MySQL will prompt you for your password. Enter the password from the user account you specified with the –u tag, and you'll connect to the MySQL server.


3 Answers

In your BATCH File :

mysql -e "set @domain=PARAMVALUE;source ./sql/update_domain.sql"

And in you SQL file :

UPDATE my_cfg SET value = @domain WHERE name = 'DOMAIN';
like image 73
L. Quastana Avatar answered Sep 19 '22 21:09

L. Quastana


you can do that with sed like this:

echo "UPDATE my_cfg SET value = '#domain#' WHERE name = 'DOMAIN'" | sed 's/#domain#/mydomain.dev/' | mysql -uusername -ppassword dbname

or update.sql has UPDATE:

cat update.sql | sed 's/#domain#/mydomain.dev/' | mysql -uusername -ppassword dbname
like image 29
Jason Heo Avatar answered Sep 18 '22 21:09

Jason Heo


This works for me:

system("(echo \"SET @domain = 'newstore.personera.abc';\"; cat sql/set_domain.sql) > /tmp/_tmp.sql")
system("mysql -uroot -hlocalhost newstore.personera.dev < /tmp/_tmp.sql")
system("rm /tmp/_tmp.sql")

...calling with system() from Capistrano.

like image 22
josef.van.niekerk Avatar answered Sep 20 '22 21:09

josef.van.niekerk