sqlite3 create table

The sqlite3 module is the standard library for working with the SQLite database in Python. It provides an interface compliant with the DB-API 2.0 specification, allowing you to easily connect to, create, and interact with SQLite databases using SQL commands directly from your Python code.

It is particularly popular because SQLite is a serverless database engine, meaning it does not require a separate server process. The entire database is stored in a single file on disk, making it lightweight and ideal for local development, small-scale applications, and embedded systems.


Key Components of the sqlite3 Module

The interaction with an SQLite database in Python is managed primarily through two main classes: Connection and Cursor.

1. Connection Objects 🔗

The Connection object manages the connection to the SQLite database file. You get this object by calling sqlite3.connect().

MethodDescription
connect(database)The main function to establish a connection. If the database file does not exist, it is created.
commit()Saves (persists) all changes made since the last call to commit() or rollback(). Crucial for making changes permanent.
rollback()Undoes all changes made since the last commit().
close()Closes the database connection. Always call this when you’re done to release the database file lock.
cursor()Returns a new Cursor object that can be used to execute SQL statements.

Export to Sheets


2. Cursor Objects 📝

The Cursor object is what you use to actually execute SQL commands and fetch results. You get a Cursor object by calling the cursor() method on a Connection object.

MethodDescription
execute(sql, parameters=())Executes a single SQL statement. Use ? as placeholders in the SQL and pass values in the parameters tuple/list.
executemany(sql, seq_of_parameters)Executes a single SQL statement against all parameter sequences found in the sequence of parameters. Used for bulk inserts or updates.
executescript(sql_script)Executes multiple SQL statements provided as a single string (a script).
fetchone()Fetches the next row of a query result set, returning a tuple, or None when no more data is available.
fetchall()Fetches all remaining rows of a query result set, returning a list of tuples.
fetchmany(size=cursor.arraysize)Fetches the next set of rows (default is 1). Returns a list of tuples.

Export to Sheets


Example Usage Flow:

  1. Connect: conn = sqlite3.connect('example.db')
  2. Cursor: c = conn.cursor()
  3. Execute: c.execute("CREATE TABLE users (id, name)")
  4. Commit: conn.commit()
  5. Close: conn.close()

Connect to or create a database file named company.db.

Create the dept table.

Create the emp (employee) table with a Foreign Key linking it to the dept table.

Python

import sqlite3
import os

# Define the database file name
DB_FILE = 'company.db'

# --- Optional: Clean up previous file for a fresh start ---
# You can remove these lines if you want to keep data
if os.path.exists(DB_FILE):
    os.remove(DB_FILE)
# -----------------------------------------------------------

# Connect to the SQLite database (or create it if it doesn't exist)
# The connection is automatically established here.
conn = sqlite3.connect(DB_FILE)
print(f"Successfully connected to the database: {DB_FILE}")

# Create a cursor object to execute SQL commands
cursor = conn.cursor()

# 1. Create the 'dept' table
print("Creating 'dept' table...")
cursor.execute('''
    CREATE TABLE dept (
        deptno INTEGER PRIMARY KEY,
        dname TEXT NOT NULL,
        loc TEXT
    );
''')
print(" 'dept' table created.")

# 2. Create the 'emp' (employee) table
# Includes a Foreign Key (deptno) referencing the 'dept' table
print("Creating 'emp' table...")
cursor.execute('''
    CREATE TABLE emp (
        empno INTEGER PRIMARY KEY,
        ename TEXT NOT NULL,
        job TEXT,
        mgr INTEGER,
        hiredate TEXT,
        sal REAL,
        comm REAL,
        deptno INTEGER,
        FOREIGN KEY (deptno) REFERENCES dept (deptno)
    );
''')
print(" 'emp' table created.")

# Commit the changes to make them permanent
conn.commit()
print("Tables created and changes committed successfully.")

# Close the connection
conn.close()
print("Database connection closed.")

Similar Posts

  • Python Modules: Creation and Usage Guide

    Python Modules: Creation and Usage Guide What are Modules in Python? Modules are simply Python files (with a .py extension) that contain Python code, including: They help you organize your code into logical units and promote code reusability. Creating a Module 1. Basic Module Creation Create a file named mymodule.py: python # mymodule.py def greet(name): return f”Hello, {name}!”…

  • Linear vs. Scalar,Homogeneous vs. Heterogeneous 

    Linear vs. Scalar Data Types in Python In programming, data types can be categorized based on how they store and organize data. Two important classifications are scalar (atomic) types and linear (compound) types. 1. Scalar (Atomic) Data Types 2. Linear (Compound/Sequential) Data Types Key Differences Between Scalar and Linear Data Types Feature Scalar (Atomic) Linear (Compound) Stores Single…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  • Class06,07 Operators, Expressions

    In Python, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality: ⚙️ 1. Arithmetic Operators ➕➖✖️➗ Used for mathematical operations: Python 2. Assignment Operators ➡️ Assign values to variables (often combined with arithmetic): Python 3. Comparison Operators ⚖️ Compare values → return True or False: Python…

  • difference between positional and keyword arguments

    1. Positional Arguments How they work: The arguments you pass are matched to the function’s parameters based solely on their order (i.e., their position). The first argument is assigned to the first parameter, the second to the second, and so on. Example: python def describe_pet(animal_type, pet_name): “””Display information about a pet.””” print(f”\nI have a {animal_type}.”) print(f”My {animal_type}’s name…

  • Formatting Date and Time in Python

    Formatting Date and Time in Python Python provides powerful formatting options for dates and times using the strftime() method and parsing using strptime() method. 1. Basic Formatting with strftime() Date Formatting python from datetime import date, datetime # Current date today = date.today() print(“Date Formatting Examples:”) print(f”Default: {today}”) print(f”YYYY-MM-DD: {today.strftime(‘%Y-%m-%d’)}”) print(f”MM/DD/YYYY: {today.strftime(‘%m/%d/%Y’)}”) print(f”DD-MM-YYYY: {today.strftime(‘%d-%m-%Y’)}”) print(f”Full month: {today.strftime(‘%B %d, %Y’)}”) print(f”Abbr…

Leave a Reply

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