# Turso 快速入门（通过 HTTP 的 SQL）

> 通过几个简单步骤，开始使用 Turso 的 SQL over HTTP。
> Canonical HTML: https://tursodb.cn/zh-cn/docs/sdk/http/quickstart/
> Upstream Source (MIT): https://docs.turso.tech/sdk/http/quickstart
> Language: zh-CN

---
在本快速入门中，我们将学习如何：

* 连接到远程 Turso 数据库
* 使用 [SQL over HTTP](https://github.com/tursodatabase/libsql/blob/main/docs/HRANA_3_SPEC.md#hrana-over-http) 执行 SQL 查询

| | `@tursodatabase/serverless` | `@libsql/client` | 原始 HTTP |
| - | - | - | - |
| **适用场景** | [Turso](/zh-cn/docs/tursodb/quickstart/) 数据库 | [libSQL](/zh-cn/docs/libsql/) 数据库 | 任意数据库 |
| **依赖项** | 仅使用 `fetch` — 零原生依赖 | 需要 Node.js 或 `/web` 子路径 | 无（任意 HTTP 客户端） |
| **ORM 支持** | 尚不支持 | Drizzle、Prisma 等 | 不适用 |

请根据数据库引擎选择驱动：Turso 数据库使用 **`@tursodatabase/serverless`**，libSQL 数据库使用 **`@libsql/client`**。

<div class="doc-tabs" data-doc-tabs>
<div class="doc-tab-list" role="tablist">
<button type="button" role="tab" class="doc-tab-btn is-active" aria-selected="true" data-tab-idx="0">@tursodatabase/serverless</button>
<button type="button" role="tab" class="doc-tab-btn" aria-selected="false" data-tab-idx="1">@libsql/client</button>
<button type="button" role="tab" class="doc-tab-btn" aria-selected="false" data-tab-idx="2">原始 HTTP</button>
</div>
<div class="doc-tab-panel is-active" role="tabpanel" data-tab-panel="0">

`@tursodatabase/serverless` 包仅使用 `fetch` API 连接 Turso——没有原生依赖，使其成为边缘和无服务器运行时中最小的选项。

**1. 安装**

```bash
npm install @tursodatabase/serverless
```

**2. 连接并查询**

```typescript
import { connect } from "@tursodatabase/serverless";

const conn = connect({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

const stmt = await conn.prepare("SELECT * FROM users WHERE id = ?");
const row = await stmt.get([123]);
```

为了与 libSQL 客户端 API 兼容，请使用 compat 模块：

```typescript
import { createClient } from "@tursodatabase/serverless/compat";

const client = createClient({
  url: process.env.TURSO_DATABASE_URL,
  authToken: process.env.TURSO_AUTH_TOKEN,
});

const result = await client.execute("SELECT * FROM users WHERE id = ?", [123]);
```

</div>
<div class="doc-tab-panel" role="tabpanel" data-tab-panel="1" hidden>

`@libsql/client` 包是 Turso 生态中广泛使用的生产级 libSQL 驱动。在无服务器和边缘运行时中使用 `/web` 导入。

**1. 安装**

```bash
npm install @libsql/client
```

**2. 连接并查询**

```typescript
import { createClient } from "@libsql/client/web";

const client = createClient({
  url: process.env.TURSO_DATABASE_URL!,
  authToken: process.env.TURSO_AUTH_TOKEN!,
});

const result = await client.execute({
  sql: "SELECT * FROM users WHERE id = ?",
  args: [123],
});
```

> [!NOTE]
>
> 在边缘和无服务器运行时中，请使用 `@libsql/client/web` 而不是 `@libsql/client`。`/web` 导入使用 HTTP 协议。

</div>
<div class="doc-tab-panel" role="tabpanel" data-tab-panel="2" hidden>

你也可以使用任意 HTTP 客户端直接通过 HTTP 发送查询。

**1. 创建 HTTP 数据库 URL**

使用 [Turso CLI](https://docs.turso.tech/cli) 或 [Platform API](https://docs.turso.tech/api-reference) 获取数据库 URL：

```bash
turso db show <database-name> --http-url
```

> [!NOTE]
>
> 将 `/v2/pipeline` 追加到 URL 后继续。

**2. 创建数据库认证令牌**

使用 Turso CLI 或 Platform API 为数据库创建新的认证令牌：

```bash
turso db tokens create <database-name>
```

**3. 创建 JSON 请求负载**

我们将使用 JSON 发送查询，因此先创建一个 JSON 负载，用于执行 SQL 语句并立即关闭连接：

```json
{
  "requests": [
    { "type": "execute", "stmt": { "sql": "SELECT * FROM users" } },
    { "type": "close" }
  ]
}
```

> [!NOTE]
>
> 请确保更新 `stmt.sql`，从你已有的表中选择数据。
>
> 绑定参数示例见[参考页面](/zh-cn/docs/sdk/http/reference/#parameter-binding)，

**4. 执行 HTTP 请求**

根据你使用的语言，可以使用 HTTP 客户端库将请求发送到已创建的 URL，并将 `Authorization` 请求头设置为已创建的令牌，同时将包含 SQL 语句的 JSON 作为请求体。

必须将实际接受请求的 pipeline URL——`/v2/pipeline`——追加到基础 URL 后面。

```ts JavaScript (Fetch)
const url = "https://[databaseName]-[organizationSlug].turso.io/v2/pipeline";
const authToken = "...";

fetch(url, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${authToken}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    requests: [
      { type: "execute", stmt: { sql: "SELECT * FROM users" } },
      { type: "close" },
    ],
  }),
})
  .then((res) => res.json())
  .then((data) => console.log(data))
  .catch((err) => console.log(err));
```

```ruby Ruby
require 'net/http'
require 'json'
require 'uri'

url = "https://[databaseName]-[organizationSlug].turso.io/v2/pipeline"
auth_token = "..."

uri = URI(url)
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer #{auth_token}"
request["Content-Type"] = "application/json"
request.body = JSON.generate({
  "requests": [
    { "type": "execute", "stmt": { "sql": "SELECT * FROM users" } },
    { "type": "close" }
  ]
})

begin
  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http|
    http.request(request)
  end

  puts JSON.parse(response.body)
rescue => e
  puts e.message
end
```

> [accordion] 响应
>
> 响应将是一个包含 `results` 数组的 JSON 对象，其中包含查询结果，类似如下：
>
> ```json theme={null}
> {
>   "baton": null,
>   "base_url": null,
>   "results": [
>     {
>       "type": "ok",
>       "response": {
>         "type": "execute",
>         "result": {
>           "cols": [],
>           "rows": [],
>           "affected_row_count": 0,
>           "last_insert_rowid": null,
>           "replication_index": "1"
>         }
>       }
>     },
>     {
>       "type": "ok",
>       "response": {
>         "type": "close"
>       }
>     }
>   ]
> }
> ```

如果需要为值使用占位符，可以这样做：

```json Positional
{
  "type": "execute",
  "stmt": {
    "sql": "SELECT * FROM users WHERE id = ?",
    "args": [
      {
        "type": "integer",
        "value": "1"
      }
    ]
  }
}
```

```json Named
{
  "type": "execute",
  "stmt": {
    "sql": "SELECT * FROM users WHERE name = :name OR name = $second_name OR name = @third_name",
    "named_args": [
      {
        "name": "name",
        "value": {
          "type": "text",
          "value": "Turso"
        }
      },
      {
        "name": "second_name",
        "value": {
          "type": "text",
          "value": "Not Turso"
        }
      },
      {
        "name": "third_name",
        "value": {
          "type": "text",
          "value": "Maybe Turso"
        }
      }
    ]
  }
}
```

> [!NOTE]
>
> 每个 arg 中的 `type` 字段对应列数据类型，可以是以下之一：`null`、`integer`、`float`、`text` 或 `blob`。

> [!NOTE]
>
> 在 JSON 中，`value` 是 `String`，以避免精度丢失，因为某些
> JSON 实现将所有数字视为 64 位浮点数。

</div>
</div>
