# Connecting to SQLite using Python

> Create, open and query a SQLite database from Python using the built-in sqlite3 module, step by step.

Source: https://helpcenter.ruachost.com/developers/databases/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?

- No external dependencies — `sqlite3` is included in Python.
- Perfect for lightweight applications, prototyping, and local development.
- Stores data in a single portable `.db` file.
- Supports SQL queries and transactions.

## Steps to Connect to SQLite Using Python

### Step 1: Import the `sqlite3` Module

```

```

### 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:**
- If the database file (`example.db`) exists, Python opens it; otherwise, it creates a new one.
- Always call `conn.commit()` after modifying data to save changes.
- Use `conn.close()` to properly close the connection and free resources.
- SQLite databases are portable, you can copy the `.db` file between systems.
