Skip to content

Latest commit

 

History

History
32 lines (29 loc) · 740 Bytes

create-sqlite-database-table.md

File metadata and controls

32 lines (29 loc) · 740 Bytes
title description author tags
Create SQLite Database Table
Creates a table in an SQLite database with a dynamic schema.
e3nviction
sqlite,database,table
import sqlite3

def create_table(db_name, table_name, schema):
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()])
    cursor.execute(f'''
        CREATE TABLE IF NOT EXISTS {table_name} (
            {schema_string}
        )''')
    conn.commit()
    conn.close()

# Usage:
db_name = 'example.db'
table_name = 'users'
schema = {
    'id': 'INTEGER PRIMARY KEY',
    'name': 'TEXT',
    'age': 'INTEGER',
    'email': 'TEXT'
}
create_table(db_name, table_name, schema)