Customer Information & Request
Name: Rohan Duhaney
Your magic request: "Write a code snippet to solve Imagine you have a script named database_maintenance.py designed to perform routine database maintenance tasks such as backing up data, removing old records, etc. using Python."
Email: smartduhaney@gmail.com
Dear Rohan Duhaney,
# Import necessary libraries
import datetime
import math
import random
# Define a function to generate random data for database
def generate_data():
# Generate random numbers for database records
num_records = random.randint(100, 1000)
# Create a list to store data
data = []
# Generate data for each record
for i in range(num_records):
# Generate random values for each column
id = random.randint(1, 100)
name = "Person " + str(i+1)
age = random.randint(20, 60)
salary = random.randint(50000, 100000)
# Append data for each record in a dictionary format
data.append({"id": id, "name": name, "age": age, "salary": salary})
# Return the generated data
return data
# Define a function to back up data
def backup_data(data):
# Get current date and time
now = datetime.datetime.now()
# Create a file name for backup
file_name = "backup_" + str(now.year) + "_" + str(now.month) + "_" + str(now.day) + ".txt"
# Open a file in write mode
with open(file_name, "w") as f:
# Iterate through each record in data
for record in data:
# Write data in a formatted way
f.write("ID: " + str(record["id"]) + "\tName: " + record["name"] + "\tAge: " + str(record["age"]) + "\tSalary: " + str(record["salary"]) + "\n")
# Print message
print("Data has been backed up successfully!")
# Define a function to remove old records
def remove_old_records(data):
# Get current date
today = datetime.date.today()
# Define a list to store indices of records to be removed
indices_to_remove = []
# Iterate through each record in data
for i, record in enumerate(data):
# Get the date the record was created
record_date = datetime.date(record["id"], record["age"], record["salary"])
# Calculate the difference between current date and record date
diff = today - record_date
# If the difference is more than 1 year, add index to the list
if diff.days > 365:
indices_to_remove.append(i)
# Remove old records from data
for i in sorted(indices_to_remove, reverse=True):
del data[i]
# Print message
print("Old records have been removed successfully!")
# Generate random data for database
data = generate_data()
# Print the data before any maintenance task
print("Data before maintenance:\n", data)
# Back up the data
backup_data(data)
# Remove old records
remove_old_records(data)
# Print the data after maintenance tasks
print("Data after maintenance:\n", data)