Menu

Post image 1
Post image 2
1 / 2
0

Python Database Automation: Back Up, Migrate, and Monitor SQLite/PostgreSQL

DEV Community·Brad·18 days ago
#JacAPMGv
Reading 0:00
15s threshold

Python Database Automation: Back Up, Migrate, and Monitor SQLite/PostgreSQL Database maintenance is critical but tedious. Here are Python scripts that automate backups, migrations, and health monitoring. Automated SQLite Backup import sqlite3 import shutil import os from datetime import datetime from pathlib import Path def backup_sqlite ( db_path : str , backup_dir : str , max_backups : int = 7 ) -> str : """ Create a timestamped backup of an SQLite database. """ backup_dir = Path ( backup_dir ) backup_dir . mkdir ( parents = True , exist_ok = True ) timestamp = datetime . now (). strftime ( " %Y%m%d_%H%M%S " ) db_name = Path ( db_path ). stem backup_file = backup_dir / f " { db_name } _ { timestamp } .db " # Use SQLite's backup API (safe even with active connections) source = sqlite3 . connect ( db_path ) dest = sqlite3 . connect ( str ( backup_file )) with dest : source . backup ( dest ) source . close () dest .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More