delete some old file
This commit is contained in:
54
Scripts/python/mysql_cleaning/delete_old_records.py
Normal file
54
Scripts/python/mysql_cleaning/delete_old_records.py
Normal file
@@ -0,0 +1,54 @@
|
||||
import mysql.connector
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# MySQL connection details
|
||||
MYSQL_HOST = "10.102.1.65"
|
||||
MYSQL_USER = "svc.emailtopdf"
|
||||
MYSQL_PASSWORD = "zZUHrps62skLKfr9yQwQ"
|
||||
MYSQL_DATABASE = "emailtopdf"
|
||||
MYSQL_TABLE = "emailtopdf"
|
||||
DATE_COLUMN = "timestamp"
|
||||
|
||||
def delete_old_records():
|
||||
"""
|
||||
Deletes records older than one week from the specified MySQL table.
|
||||
"""
|
||||
try:
|
||||
# Connect to the MySQL database
|
||||
conn = mysql.connector.connect(
|
||||
host=MYSQL_HOST,
|
||||
user=MYSQL_USER,
|
||||
password=MYSQL_PASSWORD,
|
||||
database=MYSQL_DATABASE
|
||||
)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Calculate the date one week ago
|
||||
one_week_ago = datetime.now() - timedelta(days=7)
|
||||
formatted_date = one_week_ago.strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
# SQL query to delete old records
|
||||
query = f"DELETE FROM {MYSQL_TABLE} WHERE {DATE_COLUMN} < %s"
|
||||
|
||||
# Execute the query
|
||||
cursor.execute(query, (formatted_date,))
|
||||
|
||||
# Get the number of deleted rows
|
||||
deleted_rows = cursor.rowcount
|
||||
|
||||
# Commit the transaction
|
||||
conn.commit()
|
||||
|
||||
print(f"Successfully deleted {deleted_rows} records older than one week.")
|
||||
|
||||
except mysql.connector.Error as err:
|
||||
print(f"Error: {err}")
|
||||
finally:
|
||||
# Close the connection
|
||||
if 'conn' in locals() and conn.is_connected():
|
||||
cursor.close()
|
||||
conn.close()
|
||||
print("MySQL connection is closed.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
delete_old_records()
|
||||
1
Scripts/python/mysql_cleaning/requirements.txt
Normal file
1
Scripts/python/mysql_cleaning/requirements.txt
Normal file
@@ -0,0 +1 @@
|
||||
mysql-connector-python
|
||||
Reference in New Issue
Block a user