> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 使用 Neon 的无服务器 Postgres 结合 Bun

[Neon](https://neon.tech/) 是一个全托管的无服务器 Postgres。Neon 将计算与存储分离，提供现代开发者功能，如自动扩缩容、分支、无限存储等。

***

开始步骤：创建一个项目目录，使用 `bun init` 初始化该目录，并添加 [Neon 无服务器驱动](https://github.com/neondatabase/serverless/) 作为项目依赖。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
mkdir bun-neon-postgres
cd bun-neon-postgres
bun init -y
bun add @neondatabase/serverless
```

***

创建一个 `.env.local` 文件，并将你的 [Neon Postgres 连接字符串](https://neon.tech/docs/connect/connect-from-any-app) 添加进去。

```ini .env.local icon="settings" theme={"theme":{"light":"github-light","dark":"dracula"}}
DATABASE_URL=postgresql://usertitle:password@ep-adj-noun-guid.us-east-1.aws.neon.tech/neondb?sslmode=require
```

***

将以下代码粘贴到你项目的 `index.ts` 文件中。

```ts index.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
import { neon } from "@neondatabase/serverless";

// Bun 会自动从 .env.local 加载 DATABASE_URL
// 参考：https://bun.com/docs/runtime/environment-variables 获取更多信息
const sql = neon(process.env.DATABASE_URL);

const rows = await sql`SELECT version()`;

console.log(rows[0].version);
```

***

使用 `bun ./index.ts` 启动程序，Postgres 版本会打印到控制台。

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun ./index.ts
```

```txt theme={"theme":{"light":"github-light","dark":"dracula"}}
PostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
```

***

此示例使用了 Neon 无服务器驱动的基于 HTTP 的 SQL 功能。Neon 的无服务器驱动还提供了 `Client` 和 `Pool` 构造函数，用于支持会话、交互式事务以及兼容 node-postgres。

完整内容请参阅 [Neon 文档](https://neon.tech/docs/serverless/serverless-driver) 了解无服务器驱动的详细介绍。
