r

import sqlite3
from pathlib import Path

def create_database(db_name: str, table_sql: str = None):
    """
    Create a new SQLite database file and an optional table.

    Parameters:
        db_name (str): Name or path of the SQLite database file.
        table_sql (str): Optional SQL string to create a table.
                         Example:
                         "CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)"
    """
    db_path = Path(db_name)

    try:
        # Connect to SQLite (creates the file if it doesn't exist)
        conn = sqlite3.connect(db_path)
        print(f"Database created at: {db_path.resolve()}")

        if table_sql:
            conn.execute(table_sql)
            print("Table created successfully.")

        conn.commit()
    except sqlite3.Error as e:
        print(f"SQLite error: {e}")
    finally:
        if conn:
            conn.close()

# Example usage:
if __name__ == "__main__":
    create_database(
        "my_database.db",
        "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)"
    )

Comments

Popular posts from this blog

Crypto Market Update – August 7, 2025