Akash Nil
Akash Nil

Reputation: 703

Delete older data from MySQL database using Python

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"

Upvotes: 3

Views: 2082

Answers (2)

user5069269
user5069269

Reputation:

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)

Upvotes: 2

Misa Lazovic
Misa Lazovic

Reputation: 2823

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.

Upvotes: 1

Related Questions