> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-detect-table-modification.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 clickhouse-local 数据库

> 了解如何在 chDB 中使用 clickhouse-local 数据库

[clickhouse-local](/zh/concepts/features/tools-and-utilities/clickhouse-local) 是一个内嵌了 ClickHouse 的 CLI 工具。
它让用户无需安装服务器，也能使用 ClickHouse 的强大功能。
在本指南中，我们将学习如何在 chDB 中使用 clickhouse-local 数据库。

<div id="setup">
  ## 准备工作
</div>

首先创建一个虚拟环境：

```bash theme={null}
python -m venv .venv
source .venv/bin/activate
```

现在安装 chDB。
请确保您使用的是 2.0.2 或更高版本：

```bash theme={null}
pip install "chdb>=2.0.2"
```

现在，我们来安装 [ipython](https://ipython.org/)：

```bash theme={null}
pip install ipython
```

我们将使用 `ipython` 来执行本指南其余部分中的命令，你可以运行以下命令来启动它：

```bash theme={null}
ipython
```

<div id="installing-clickhouse-local">
  ## 安装 clickhouse-local
</div>

下载和安装 clickhouse-local 的方法与[下载和安装 ClickHouse](/zh/get-started/setup/install)相同。
我们可以运行以下命令来完成此操作：

```bash theme={null}
curl https://clickhouse.com/ | sh
```

要启动 clickhouse-local 并将数据持久化到某个目录，需要传入 `--path`：

```bash theme={null}
./clickhouse -m --path demo.chdb
```

<div id="ingesting-data-into-clickhouse-local">
  ## 向 clickhouse-local 导入数据
</div>

默认数据库中的数据只存储在内存中，因此我们需要创建一个命名数据库，以确保导入的任何数据都会持久化到磁盘。

```sql theme={null}
CREATE DATABASE foo;
```

创建一个表并插入一些随机数：

```sql theme={null}
CREATE TABLE foo.randomNumbers
ORDER BY number AS
SELECT rand() AS number
FROM numbers(10_000_000);
```

我们来写一个查询，看看当前有哪些数据：

```sql theme={null}
SELECT quantilesExact(0, 0.5, 0.75, 0.99)(number) AS quants
FROM foo.randomNumbers
```

```response theme={null}
┌─quants────────────────────────────────┐
│ [69,2147776478,3221525118,4252096960] │
└───────────────────────────────────────┘
```

完成后，请务必在 CLI 中执行 `exit;` 退出，因为同一时间只能有一个进程持有该目录的锁。
否则，当我们尝试通过 chDB 连接到数据库时，就会出现以下错误：

```text theme={null}
ChdbError: Code: 76. DB::Exception: Cannot lock file demo.chdb/status. Another server instance in same directory is already running. (CANNOT_OPEN_FILE)
```

<div id="connecting-to-a-clickhouse-local-database">
  ## 连接到 clickhouse-local 数据库
</div>

返回 `ipython` shell，并从 chDB 导入 `session` 模块：

```python theme={null}
from chdb import session as chs
```

初始化一个指向 `demo.chdb` 的会话：

```python theme={null}
sess = chs.Session("demo.chdb")
```

然后，我们可以运行同一个查询，以返回数值的分位数：

```python theme={null}
sess.query("""
SELECT quantilesExact(0, 0.5, 0.75, 0.99)(number) AS quants
FROM foo.randomNumbers
""", "Vertical")

Row 1:
──────
quants: [0,9976599,2147776478,4209286886]
```

我们也可以通过 chDB 向该数据库插入数据：

```python theme={null}
sess.query("""
INSERT INTO foo.randomNumbers
SELECT rand() AS number FROM numbers(10_000_000)
""")

Row 1:
──────
quants: [0,9976599,2147776478,4209286886]
```

然后，我们可以在 chDB 或 clickhouse-local 中再次运行该分位数查询。
