> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/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={null}
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={null}
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/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
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={null}
bun ./index.ts
```

```txt theme={null}
PostgreSQL 16.2 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit
```

***

本示例使用了 Neon 无服务器驱动的 SQL-over-HTTP 功能。Neon 的无服务器驱动还暴露了 `Client` 和 `Pool` 构造函数，以支持会话、交互式事务和 node-postgres 兼容性。

请参考 [Neon 文档](https://neon.tech/docs/serverless/serverless-driver) 了解无服务器驱动的完整概述。
