SQL Query not working inside a shell script

Sagar Mandal :

I really need help on this one... so I'm writing this shell script which basically connects to MySQL database and fetches the data and give the output as a CSV file.

I'm able to connect to database and also able to get data from a simple query "select * from test_table;"

but when I try to write this query to make the give output as csv file from script it's giving an a syntax error.

QUERY> "select * into outfile '/Path/.cvs' fields terminated by ',' lines terminated by '\n' from test_table;"

this query is not working inside the script but it is working in MySQL database (CLI).

Really need help on this guys, if there is any way around of making output as csv file do tell me otherwise helpme out on this..

Error Msg I get is "ERROR 1064 (42000)" I know it's a syntax error but its only not working inside the script otherwise I don't how its working in mysql.

#!/usr/bin/bash

#scirpt to connect with db

master_db_user='root'
master_db_passwd='123'
master_db_port='3306'
master_db_host='localhost'
master_db_name='sagar_tb'


#Preparing script 

SQL_Query='select * INTO OUTFILE '/created_files/RESULT3.CSV' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' from test_table;'

#MySql Command to connect to a database 

mysql -u$master_db_user -p$master_db_passwd -P$master_db_port -h$master_db_host -D$master_db_name <<EOF
$SQL_Query
EOF
echo "End of the Script"

Really need help here guys

thanks and regards, Sagar Mandal

dash-o :

The script tries to construct the command into SQL_Query. However, the implementation does take into account the quoting rules (you have to escape the quotes like ',')

SQL_Query='select * INTO OUTFILE '/created_files/RESULT3.CSV' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' from test_table;'

For simple solution, just inline the SQL into the mysql command (formatted for readability). Using the Here document ('<

mysql ... <<EOF
select * INTO OUTFILE '/created_files/RESULT3.CSV' ...
EOF

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=407955&siteId=1