3

I want to delete records older than 7 days automatically, but it doesn't work. Message is showing that older data is deleted, but actually it did not delete the data.

My code is:

try:
    db= MySQLdb.connect("localhost","root","","testDB")
    cursor=db.cursor()
    sql="DELETE FROM CALLRECORD WHERE DATE< DATE_SUB(NOW(), INTERVAL 7 DAY)"
    try:
        cursor.execute(sql)
        db.commit()
        print "Deleted Older Data from database"

    except:
        db.rollback()
        print "Cann't delete older data"
    db.close()

except:
    print "localserver not connected"
3
  • Hey @Akash Nil did you try changing the operator? Did it work? Commented Feb 2, 2016 at 12:12
  • sorry for the delay < did not work @ misa lazovic Commented Feb 3, 2016 at 9:21
  • as my stored date format in callrecord is dd/mm/yy so I tried sql="DELETE FROM CALLRECORD WHERE DATE< GET_FORMAT( DATE_SUB(NOW(), INTERVAL 7 DAY),'EUR')" but it shows error Commented Feb 4, 2016 at 12:26

2 Answers 2

2

I think you've made a mistake in your query, you are deleting records which inserted in last 7 days. Use below query instead of yours:

DELETE FROM CALLRECORD
WHERE DATE < DATE_SUB(NOW(), INTERVAL 7 DAY)
Sign up to request clarification or add additional context in comments.

4 Comments

my stored date format is dd/mm/yy when i am using your code it deleting current record. i am using linux for database. i tested WHERE DATE < DATE_SUB(NOW(date +'%d-%m-%y'), INTERVAL 7 DAY) but the result is same. if i am using > sign it did not delete data
Try UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY))
in my database data coming every minutes your code deleted all the record
date entered my callrecord by python command date=datetime.now().strftime("%d/%m/%y"). then this date related information will stored into callrecord after that it will delete older data suppose stored date is 21/01/16. and it will delete all the record before 14/01/16.
1

You are using > instead of <, so you're deleting new records instead of old ones. You need to delete records with date LESS (not greater) than the date that was seven days ago.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.