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

  • 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…

  • Python Primitive Data Types & Functions: Explained with Examples

    1. Primitive Data Types Primitive data types are the most basic building blocks in Python. They represent simple, single values and are immutable (cannot be modified after creation). Key Primitive Data Types Type Description Example int Whole numbers (positive/negative) x = 10 float Decimal numbers y = 3.14 bool Boolean (True/False) is_valid = True str…

  • Examples of Python Exceptions

    Comprehensive Examples of Python Exceptions Here are examples of common Python exceptions with simple programs: 1. SyntaxError 2. IndentationError 3. NameError 4. TypeError 5. ValueError 6. IndexError 7. KeyError 8. ZeroDivisionError 9. FileNotFoundError 10. PermissionError 11. ImportError 12. AttributeError 13. RuntimeError 14. RecursionError 15. KeyboardInterrupt 16. MemoryError 17. OverflowError 18. StopIteration 19. AssertionError 20. UnboundLocalError…

  • Dictionaries

    Python Dictionaries: Explanation with Examples A dictionary in Python is an unordered collection of items that stores data in key-value pairs. Dictionaries are: Creating a Dictionary python # Empty dictionary my_dict = {} # Dictionary with initial values student = { “name”: “John Doe”, “age”: 21, “courses”: [“Math”, “Physics”, “Chemistry”], “GPA”: 3.7 } Accessing Dictionary Elements…

  • Indexing and Slicing in Python Lists Read

    Indexing and Slicing in Python Lists Read Indexing and slicing are fundamental operations to access and extract elements from a list in Python. 1. Indexing (Accessing Single Elements) Example 1: Basic Indexing python fruits = [“apple”, “banana”, “cherry”, “date”, “fig”] # Positive indexing print(fruits[0]) # “apple” (1st element) print(fruits[2]) # “cherry” (3rd element) # Negative indexing print(fruits[-1]) # “fig”…

  • File Handling in Python

    File Handling in Python File handling is a crucial aspect of programming that allows you to read from and write to files. Python provides built-in functions and methods to work with files efficiently. Basic File Operations 1. Opening a File Use the open() function to open a file. It returns a file object. python # Syntax: open(filename,…

Leave a Reply

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