Connecting to SQLite using Python
SQLite is a lightweight, serverless database engine included with Python’s standard library. On ruachost.com, you can connect to SQLite databases using the built‑in sqlite3 module without installing any third‑party packages.
Why Use Python with SQLite?
Section titled “Why Use Python with SQLite?”- No external dependencies —
sqlite3is included in Python. - Perfect for lightweight applications, prototyping, and local development.
- Stores data in a single portable
.dbfile. - Supports SQL queries and transactions.
Steps to Connect to SQLite Using Python
Section titled “Steps to Connect to SQLite Using Python”Step 1: Import the sqlite3 Module
Section titled “Step 1: Import the sqlite3 Module”import sqlite3Step 2: Create or Open a Database
Section titled “Step 2: Create or Open a Database”# Connect to a database file (creates it if it doesn’t exist)conn = sqlite3.connect('example.db')Step 3: Create a Cursor
Section titled “Step 3: Create a Cursor”curs = conn.cursor()Step 4: Run SQL Commands
Section titled “Step 4: Run SQL Commands”# Create a tablecurs.execute("CREATE TABLE employees (firstname TEXT, lastname TEXT, title TEXT);")
# Insert datacurs.execute("INSERT INTO employees VALUES ('Kelly', 'Koe', 'Engineer');")
# Commit changesconn.commit()
# Query datacurs.execute("SELECT firstname, lastname FROM employees;")for firstname, lastname in curs.fetchall(): print(firstname, lastname)Step 5: Close the Connection
Section titled “Step 5: Close the Connection”conn.close()