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?
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.
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.
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.
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
$ 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
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