Home > database >  How to insert into mysql table from bash with quotes in values?
How to insert into mysql table from bash with quotes in values?

Time:08-04

I obtain the result of a bash file process into a variable. The variable content should be inserted into a mysql table from bash cmd:

content="File '/test.csv' was imported"

mysql --user=root --password=rootpw --database=$DB
    -e "INSERT INTO mytable VALUES(1, '$content')"

Result:

ERROR 1064 (42000) at line 1: 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 '' was imported' at line 1

Question: how can I deal with single quotes contained in a variable, when inserting to mysql?

I tried all variants of $content, '$content' and "$content", but none of them worked.

CodePudding user response:

Internal quotes need to be doubled. Try

mysql --user=root --password=rootpw --database=$DB
    -e "INSERT INTO mytable VALUES(1, '${content//\'/\'\'}')"
  • Related