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?
-
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
Step 1: Import the sqlite3 Module
import sqlite3
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
curs = conn.cursor()
Step 4: Run SQL Commands
# Create a table
curs.execute("CREATE TABLE employees (firstname TEXT, lastname TEXT, title TEXT);")
# Insert data
curs.execute("INSERT INTO employees VALUES ('Kelly', 'Koe', 'Engineer');")
# Commit changes
conn.commit()
# Query data
curs.execute("SELECT firstname, lastname FROM employees;")
for firstname, lastname in curs.fetchall():
print(firstname, lastname)
Step 5: Close the Connection
conn.close()
Important Notes
|