When I attempt to execute a multi-line SQL in mysql via shell script:
mysql -uroot -ppass mydb <<<EOF
SELECT * INTO OUTFILE 'table.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM mytable limit 1;
EOF
I get a syntax error:
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 'EOF' at line 1
What's the right way to script it?
sh script to execute multiple MySQL commands. mysql -h$host -u$user -p$password -e "drop database $dbname;" mysql -h$host -u$user -p$password -e "create database $dbname;" mysql -h$host -u$user -p$password -e "another MySQL command" ...
Multiple statements or multi queries must be executed with mysqli::multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.
Learn MySQL from scratch for Data Science and Analytics To run SQL script in MySQL, use the MySQL workbench. First, you need to open MySQL workbench. Now, File -> Open SQL Script to open the SQL script. Note − Press OK button twice to connect with MySQL.
Run queries with “-e” option Basically, if you merely want to run a simple and short SQL query, use the -e option following the query. As the above code shows, the -D option is to specify which database to use and the -e option can execute a query.
The syntax for bash heredoc is:
COMMAND <<InputComesFromHERE
...
...
...
InputComesFromHERE
So you have an extra <
.
In order to prepare and test you can replace COMMAND
(i.e. mysql -uroot -ppass mydb
in this case) with cat
to have a look at the exact SQL code that will be executed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With