0

Is it possible to use shell variable in a mysql query via command line? What I want to do is :

$ var='test'

$ mysql -e 'INSERT INTO table (text) VALUE ($var);' database

It didn't seems to work, even when I use ${var}

Any idea of how I can do something like that?

I have to stay in the shell, as I am running this through a jenkins 'execute shell'

JGV
  • 5,037
  • 9
  • 50
  • 94
guyzmuch
  • 13
  • 2
  • 2
    You need to double-quote the outer SQL string for the variable to be expanded, and you need to single-quote `'$var'` inside the SQL because it is a string literal. See [When to use single quotes, double quotes, backticks](http://stackoverflow.com/a/11321508/541091) <-- That is in context of PHP, but almost the same situation with a shell. – Michael Berkowski Jul 09 '15 at 14:52
  • What is the source of the variable `var`? If it results from some other command's output as opposed to hard-coding a variable, you may have to worry about SQL injection or at the very least, proper escaping so it does not break the SQL statement. – Michael Berkowski Jul 09 '15 at 14:57
  • @MichaelBerkowski Yes, my problem was all a quotes problem, and I manage to fix it. The 'var' source was a command > reading a json file. In the end what I wanted to do didn't work out, json file was loosing it's quotes. And so I moved to an other solutions than doing a mysql request. thanks any, it was good knowledge – guyzmuch Jul 10 '15 at 14:10
  • You should post an answer below with what became your solution. – Michael Berkowski Jul 10 '15 at 14:12

1 Answers1

0

So, with the help of the comment, I finally manage to do it.

The link explanations of quotes in mysql explain everything.

The solution :

$ var='test'
$ mysql -e "INSERT INTO table (text) VALUE ('$var');" database
Community
  • 1
  • 1
guyzmuch
  • 13
  • 2