# Python 中使用 SQLite

URL: https://caijiao.org/sqlite/lang/python
Source: docs/sqlite/lang/python.md
Description: 本章节介绍如何在 Python 中使用 SQLite，包括连接数据库、执行 SQL 语句和处理结果，帮助快速实现轻量级数据存储和操作。

Python 内置 `sqlite3` 模块，方便与 [SQLite](/sqlite/) 数据库交互。

## 连接数据库

```python
import sqlite3

conn = sqlite3.connect('example.db')  # 连接（不存在则创建）
cursor = conn.cursor()
```

## 执行 SQL 语句

创建表：

```python
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
```

插入数据：

```python
cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))
conn.commit()
```

查询数据：

```python
cursor.execute('SELECT * FROM users')
rows = cursor.fetchall()
for row in rows:
    print(row)
```

## 关闭连接

```python
cursor.close()
conn.close()
```

通过 Python 操作 SQLite，实现轻量级数据库应用，适合小型项目和快速开发。
