How Can We Help?
Python Script: Generate SQL Dump with Structure and Data
Below is a Python script that generates a SQL dump containing both the structure (schema) and data of a specified database table:
import sqlite3
def generate_sql_dump(database_name, table_name):
# Connect to the database
conn = sqlite3.connect(database_name)
cursor = conn.cursor()
# Retrieve table structure
cursor.execute(f"PRAGMA table_info({table_name})")
columns_info = cursor.fetchall()
# Retrieve table data
cursor.execute(f"SELECT * FROM {table_name}")
table_data = cursor.fetchall()
# Generate SQL dump for table structure
sql_dump = f"CREATE TABLE {table_name} (\n"
for column_info in columns_info:
column_name = column_info[1]
data_type = column_info[2]
sql_dump += f" {column_name} {data_type},\n"
sql_dump = sql_dump.rstrip(',\n') + "\n);\n\n"
# Generate SQL dump for table data
sql_dump += f"INSERT INTO {table_name} VALUES\n"
for row in table_data:
values = ', '.join([f"'{value}'" if isinstance(value, str) else str(value) for value in row])
sql_dump += f" ({values}),\n"
sql_dump = sql_dump.rstrip(',\n') + ";\n"
# Close the connection
conn.close()
return sql_dump
# Example usage:
database_name = "example.db"
table_name = "users"
sql_dump = generate_sql_dump(database_name, table_name)
# Write SQL dump to a file
with open("database_dump.sql", "w") as f:
f.write(sql_dump)
print("SQL dump generated successfully!")
This script assumes you’re working with a SQLite database. You can adjust it accordingly if you’re using a different database system like MySQL or PostgreSQL. Also, ensure you have appropriate permissions to access the specified database and table.