Python ProgramingPython Programing

Python script to back up table data and clean the table.

Of course! Let’s dissect the process of writing a Python script to clean the table and backup its contents. The crucial actions that you can take are as follows:

Backup Table Data:

Use a Python library such as pymysql, psycopg2, or sqlite3 to establish a connection to your database (such as MySQL, PostgreSQL, or SQLite).
Take out the information you wish to backup from the table.
For safekeeping, save the data to a backup file (such as CSV, JSON, or Excel).

Cleaning Table Data:

Determine the precise cleaning duties that need to be completed. Typical chores consist of: Eliminating duplication.
Taking care of missing values (such as removing rows and columns or filling with default values).
text standardization (such as lowering the case or eliminating unusual letters).
parsing numerical values and dates.
To clean the data, write Python routines or make use of tools like numpy and pandas.
Use the cleaning guidelines on the data in your table.
Integrate Cleaning and Backup:

Write a Python script that does both cleaning and backup operations.
Define classes or functions for each task (cleaning and backup).
Run the script to clear the table and create a backup of the data.
Don’t forget to modify the preceding procedures according to your unique use case, database, and table structure. I hope your Python script turns out well!

back up of table using Python script.

Here’s how the script works:

  1. It connects to the MySQL database using the mysql-connector-python library.
  2. It creates a cursor object to execute queries on the database.
  3. It gets the current date and time to use in the backup file name.
  4. It executes a SELECT * query on the table to retrieve all the data.
  5. It writes the data to a CSV file using the csv library. The file name includes the table name and the current date and time.
  6. It truncates the table using a TRUNCATE TABLE query.
  7. It commits the changes to the database.
  8. It closes the cursor and connection.

Make sure to replace the placeholders (your_username, your_password, your_host, your_database, and your_table_name) with the actual values for your database and table.

 

import mysql.connector
import csv
import datetime

# Database connection settings
username = 'your_username'
password = 'your_password'
host = 'your_host'
database = 'your_database'
table_name = 'your_table_name'

# Create a connection to the database
cnx = mysql.connector.connect(
user=username,
password=password,
host=host,
database=database
)

# Create a cursor object to execute queries
cursor = cnx.cursor()

# Get the current date and time for the backup file name
now = datetime.datetime.now()
backup_file_name = f"{table_name}_{now.strftime('%Y-%m-%d_%H-%M-%S')}.csv"

# Backup the table data to a CSV file
with open(backup_file_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
cursor.execute(f"SELECT * FROM {table_name}")
rows = cursor.fetchall()
writer.writerow([desc[0] for desc in cursor.description]) # Write the header row
writer.writerows(rows)

print(f"Backup file saved to {backup_file_name}")

# Truncate the table
cursor.execute(f"TRUNCATE TABLE {table_name}")
cnx.commit()

print(f"Table {table_name} truncated")

# Close the cursor and connection
cursor.close()
cnx.close()


import mysql.connector
import csv
import datetime

# Database connection settings strings
username = 'db_username'
password = 'db_password'
host = 'db_host'
database = 'db_database_name'
table_name = 'db_table_name'

# Create a connection to the database
conx = mysql.connector.connect(
user=username,
password=password,
host=host,
database=database
)

# Create a cursor object to execute queries
cursor = conx.cursor()

# Get the current date and time for the backup file name
now = datetime.datetime.now()
backup_file_name = f"{table_name}_{now.strftime('%Y-%m-%d_%H-%M-%S')}.csv"

# Backup the table data to a CSV file
with open(backup_file_name, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
cursor.execute(f"SELECT * FROM {table_name}")
rows = cursor.fetchall()
writer.writerow([desc[0] for desc in cursor.description]) # Write the header row
writer.writerows(rows)

print(f"Backup file saved to {backup_file_name}")

# Truncate the table
cursor.execute(f"TRUNCATE TABLE {table_name}")
cnx.commit()

print(f"Table {table_name} truncated")

# Close the cursor and connection
cursor.close()
cnx.close()

you may like this article as well.

Coding Skills – 01 – Python Top 10 Program

You an also read this articles for more information.

Automate backup with Python Script

Leave a Reply

Your email address will not be published. Required fields are marked *

Netflix’s Overall Architecture. Gold is money every thing else is credit