Lucas Matos
Lucas Matos

Reputation: 1152

How can i set a crontab to execute a mysql query and log the output?

Well, title self describes it.. I need to run a sql function to clean some duplicated posts, i need to do it several times a day so i need to use cron...

I set a new crontab job, like this:

00 16,18,19,20,21 * * * mysql -h MY-DB-HOST.COM -u MY-DB-USERNAME -pMY-DB-PASSWORD -e "delete from hotaru_posts where post_id in ( select post_id from ( select post_id from hotaru_posts a group by post_title having count(post_title) > 1 ) b )" >> /tmp/cron_job.log

but nothing seems to be logged, so i supposed its not working.

Theres no problem with the sql sentence, thats not the issue here.

Anything wrong with my cron rule?

Upvotes: 4

Views: 35387

Answers (4)

Moutaz Salem
Moutaz Salem

Reputation: 63

execute the following in your cron configurations

echo "your_SQL_statement" | mysql --skip-column-names -udbuser -pdbpassword yourdb >> yourlog.log

Upvotes: 4

Florian
Florian

Reputation: 375

You need to use the full path to scripts executed by a cronjob. For instance if the mysql binary's location is /usr/local/mysql/bin/mysql you'd use that in your cronjob.

00 16,18,19,20,21 * * * /usr/local/mysql/bin/mysql -h MY-DB-HOST.COM -u .....

Upvotes: 2

Lucas Matos
Lucas Matos

Reputation: 1152

well, since the mysql was not working properly directly inside crontab (thought that i think that was a path issue like Alex Howansky said), i created a php file dealing this query and called the php in crontab, much easier, and give me the option to use conditions.

the cron job:

00 8,14,18,19,20,21,23 * * * /usr/local/bin/php /home/aikaforum/cata/public_html/cron_dup.php >> /cata/tmp/cron_dup.log 

the php:

<?php
$username="xxxxxxx";
$password="xxxxxx";
$dbname="xxxxxx";
$dbhost="xxxxx.xxxxx.com";
$query="delete from hotaru_posts where post_id in ( select post_id from ( select post_id from hotaru_posts a group by post_title having count(post_title) > 1 ) b )";
mysql_connect($dbhost,$username,$password);
@mysql_select_db($dbname) or die(strftime('%c')." Unable to select database");
mysql_query($query);
mysql_close();
echo strftime('%c')." ok!";
?>

Thanks for all the help.

Upvotes: 8

muffinista
muffinista

Reputation: 6736

I suspect that your script is working but isn't actually returning any output. Here's my local test:

 mysql -u username dbname -e "delete from posts" > foo             
 cat foo
 (empty file) 

Just to be clear, foo is an empty file. posts was not an empty table.

So, just to be more precise, I think that's the expected behavior of MySQL here, although I can't confirm this in their docs. If you want/need output here, you'll probably need to write a script to check your table before/after deleting.

Upvotes: 2

Related Questions