7

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?

josef.van.niekerk
  • 11,941
  • 20
  • 97
  • 157

4 Answers4

12

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';
L. Quastana
  • 1,273
  • 1
  • 12
  • 34
  • I get a syntax error unless I put a semicolon after the source command – Jeff Jul 20 '17 at 15:42
  • It looks like this may not work in mysql 5.6 ? `source` works interactively, but doesn't seem to work when passed in the `-e` parameter. – ebyrob Dec 03 '17 at 17:04
4

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
Jason Heo
  • 9,956
  • 2
  • 36
  • 64
  • And of course, in case of a sh script, use double quote in the sed part to pass the new value as variable. i.e. `cat update.sql | sed "s/#domain#/$some_var/" | mysql -uusername -ppassword dbname` – Gabriel Glenn Apr 06 '16 at 13:24
2

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.

josef.van.niekerk
  • 11,941
  • 20
  • 97
  • 157
0

I've found a better solution.

--init-command=name SQL Command to execute when connecting to MariaDB server.

mysql --init-command="SET @foo = 1; SET @bar = 2" -e "SELECT @foo, @bar, VERSION()"

Output:

+------+------+-------------------------------------+
| @foo | @bar | VERSION()                           |
+------+------+-------------------------------------+
|    1 |    2 | 10.6.3-MariaDB-1:10.6.3+maria~focal |
+------+------+-------------------------------------+

It also works with file redirection.

crash
  • 603
  • 4
  • 11