Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get return code of the mysql command

I'm writing a shell script to import a csv file in mysql, this is my code:

DATABASE=*mydatabase*
USER=*myuser*
PASS=*mypassword*

file0="myfile.csv"
if [ -e "$file0" ]
then
  mysql --user=${USER} --password=${PASS} --database= ${DATABASE} --local-infile=1 < myquery.sql
else
  echo "$file0 does not exist"
fi

The query to execute is in myquery.sql and this is its content:

LOAD DATA LOCAL INFILE 'myfile.csv' replace INTO TABLE imported_table
FIELDS TERMINATED BY ';' 
ENCLOSED BY '' 
LINES TERMINATED BY '\n' 
IGNORE 1 LINES 
(Field1, Field2, Field3, Field4, Field5);

This code works just fine, but how do I check if the query is executed? My goal is to delete the file after importation if it is successful or write to a custom log file in case of error. Any suggestion?

like image 890
Dakkar Avatar asked Jan 08 '15 15:01

Dakkar


People also ask

How do I view MySQL code?

Use the SHOW FULL TABLE FROM (or IN ) statement to get all views in a specified database. Add the LIKE clause to the SHOW FULL TABLE statement to get the views that match a pattern. Query data from the table information_schema. tables to get the views in a database.

What does MySQL query return?

Return Values ¶ For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or false on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns true on success or false on error.

Is return a keyword in MySQL?

The RETURN statement in MySQL is used to end the stored functions. Each stored function should have at least one RETURN statement. This is used only in functions in stored procedures triggers or, events you can use LEAVE instead of RETURN.


1 Answers

Whenever you run a command with mysql (or any other in Unix), you get a return code that you can check with $?. In case it was successful, it will be 0. Otherwise, it will be a different number.

So you can do:

mysql --user=${USER} --password=${PASS} --database= ${DATABASE} --local-infile=1 < myquery.sql
if [ $? -eq 0 ]; then
   # remove file
else
   # write to log
fi

Test

$ mysql -u me -pXXXX -e "SELECT COUNT(*) FROM YYY.ZZZ;"


+----------+
| COUNT(*) |
+----------+
|   123 |
+----------+
$ echo $?
0
$ mysql -u meASDFASFASD -pXXXX -e "SELECT COUNT(*) FROM YYY.ZZZ;"
ERROR 1045 (28000): Access denied for user 'meASDFASFASD'@'local' (using password: YES)
$ echo $?
1
like image 50
fedorqui 'SO stop harming' Avatar answered Sep 23 '22 14:09

fedorqui 'SO stop harming'