Skip to content
Database

连接到你的数据库

Supabase provides several ways to connect to your Postgres database, whether your code runs in the frontend, in a persistent backend, or in a serverless function.

学会如何选择连接方式以及在哪里找到它的连接字符串。

🌐 Learn how to pick a connection method and where to find the connection string for it.

有关池化的工作原理以及适用于你连接的限制,请参见 连接池和限制。

🌐 For how pooling works and the limits that apply to your connections, see Connection pooling and limits.

你用哪种连接方式?#

🌐 Which connection method do you use? [#choose-a-connection-method]

你如何连接到你的数据库取决于你的代码运行的位置。在表格中找到你的情况,然后获取匹配的连接字符串。

🌐 How you connect to your database depends on where your code runs. Find your case in the table, then get the matching connection string.

你的代码运行在哪里使用原因
一个前端应用数据 API支持 REST 或 GraphQL,所以你不需要 Postgres 客户端。需要行级安全。
无服务器或边缘函数共享连接池,事务模式这些环境会开启许多短时连接。
在 IPv6 上的持久后端,或带有 IPv4 附加功能直接连接路径中没有连接池。
在仅支持 IPv4 的网络上保持后端持久性共享连接池,会话模式每个方案中的共享连接池仅支持 IPv4。
第三方工具,例如 BI 客户端或数据库 GUI共享连接池,会话模式可以通过你不控制的网络的 IPv4 访问,并且支持预处理语句。
高性能付费应用专用连接池运行在与数据库相同的机器上,所以比共享连接池延迟更低。
迁移、pg_dump、备份和恢复,或复制直接连接这些都是单会话和 Postgres 原生命令。

有关每种模式的主机、端口和 IP 版本,请参见 Endpoints and IP versions。有关命名的 ORM 或数据库 GUI,请参见 Quickstarts。

🌐 For the host, port, and IP version of each mode, see Endpoints and IP versions. For a named ORM or database GUI, see Quickstarts.

获取你的连接字符串 #

🌐 Get your connection string [#get-your-connection-string]

从前端应用连接?你不需要连接字符串。直接跳到 数据 API 和客户端库,它使用你的项目 URL 和 API 密钥即可。

🌐 Connecting from a frontend application? You don't need a connection string. Skip to Data APIs and client libraries, which uses your project URL and an API key instead.

对于每种 Postgres 连接模式,这个字符串都来自同一个地方:

🌐 For every Postgres connection mode, the string comes from the same place:

  1. 在 Supabase 控制台 打开你的项目。
  2. 点击页面顶部的连接。
  3. 选择你上面选的连接方式。
  4. 复制这个字符串,并将 [YOUR-PASSWORD] 替换成你的数据库密码。百分号编码它包含的任何保留字符,比如 &、#、? 或空格。

以下部分展示了每个字符串的样子以及何时使用它。请从你复制的字符串中获取主机、端口和用户名,而不是直接输入括号里的占位符。尤其是 pooler 主机不能根据你的地区自行组成,并且池化连接使用的用户名与直接连接不同。两者都在 Endpoints 和 IP 版本中有说明。

🌐 The sections below show what each string looks like and when to use it. Take the host, port, and username from the string you copied rather than typing the bracketed placeholders literally. The pooler host in particular can't be composed from your region, and pooled connections use a different username from direct connections. Both are covered under Endpoints and IP versions.

直接连接 #

🌐 Direct connection [#direct-connection]

直接连接字符串可以直接连接到你的 Postgres 实例。把它用于持久化后端,比如虚拟机(VM)和长时间运行的容器。例子包括 AWS EC2 机器、Fly.io VM 和 DigitalOcean Droplets。

🌐 The direct connection string connects directly to your Postgres instance. Use it for persistent backends, such as virtual machines (VMs) and long-running containers. Examples include AWS EC2 machines, Fly.io VMs, and DigitalOcean Droplets.

postgresql://postgres:[YOUR-PASSWORD]@db.[PROJECT-REF].supabase.co:5432/postgres

通过点击 Connect 从 Supabase 仪表板获取这个字符串。

🌐 Get this string from the Supabase Dashboard by clicking Connect.

共享池器,会话模式 #

🌐 Shared pooler, session mode [#pooler-session-mode]

会话模式连接字符串通过共享池连接到你的 Postgres 实例。当你从仅支持 IPv4 的网络连接时,可以把它当作直接连接的替代方案使用。

🌐 The session mode connection string connects to your Postgres instance through the shared pooler. Use it as an alternative to a direct connection when you connect from an IPv4-only network.

postgresql://postgres.[PROJECT-REF]:[YOUR-PASSWORD]@[POOLER-HOST]:5432/postgres

在 Supabase 仪表板上点击 Connect 并选择 Session pooler 来获取这个字符串。

🌐 Get this string from the Supabase Dashboard by clicking Connect and choosing Session pooler.

共享连接池器,事务模式 #

🌐 Shared pooler, transaction mode [#pooler-transaction-mode]

事务模式连接字符串通过事务池模式连接到你的 Postgres 实例的共享连接池。适用于使用许多短期连接的无服务器和边缘函数。

🌐 The transaction mode connection string connects to your Postgres instance through the shared pooler in transaction-pooling mode. Use it for serverless and edge functions, which open many short-lived connections.

postgresql://postgres.[PROJECT-REF]:[YOUR-PASSWORD]@[POOLER-HOST]:6543/postgres

在 Supabase 仪表板上点击 Connect 并选择 Transaction pooler 来获取这个字符串。

🌐 Get this string from the Supabase Dashboard by clicking Connect and choosing Transaction pooler.

专用池子 #

🌐 Dedicated pooler [#dedicated-pooler]

在付费计划中,Supabase 会为你的 Postgres 数据库提供一个专用的连接池。该专用连接池只以事务模式运行。若需会话模式,请使用 共享连接池。它可以通过 IPv6 访问,如果项目有 IPv4 附加功能,也可以通过 IPv4 访问。

🌐 On paid plans, Supabase provisions a dedicated pooler that runs alongside your Postgres database. The dedicated pooler runs in transaction mode only. For session mode, use the shared pooler. It is reachable over IPv6, or over IPv4 if the project has the IPv4 add-on.

postgresql://postgres:[YOUR-PASSWORD]@db.[PROJECT-REF].supabase.co:6543/postgres

通过点击 Connect 从 Supabase 仪表板获取这个字符串。

🌐 Get this string from the Supabase Dashboard by clicking Connect.

数据 API 和客户端库 #

🌐 Data APIs and client libraries [#data-apis-and-client-libraries]

数据 API 让你可以使用 REST 或 GraphQL 请求与数据库交互。只要你的表启用了 行级安全 (RLS) 并且有允许访问的策略,你就可以用这些 API 从前端获取和插入数据。如果启用了 RLS 但没有策略,则所有请求都会被拒绝。

🌐 The Data APIs let you interact with your database using REST or GraphQL requests. You can use these APIs to fetch and insert data from the frontend, as long as your tables have Row Level Security (RLS) enabled and policies that allow the access. RLS with no policies denies every request.

为了方便,你也可以使用 Supabase 客户端库,它们为开发者提供了友好的接口,并帮你处理认证:

🌐 For convenience, you can also use the Supabase client libraries, which wrap the Data APIs with a developer-friendly interface and handle authentication for you:

端点和IP版本 #

🌐 Endpoints and IP versions [#endpoints-and-ip-versions]

每种模式都有自己的主机、端口和 IP 版本支持。IP 版本支持取决于你的套餐以及项目是否有 IPv4 附加组件。

🌐 Each mode has its own host, port, and IP version support. IP version support depends on your plan and on whether the project has the IPv4 add-on.

模式主机:端口免费付费付费 + IPv4 附加
直接连接db.[PROJECT-REF].supabase.co:5432IPv6IPv6IPv4
共享池,Session 模式aws-[INDEX]-[REGION].pooler.supabase.com:5432IPv4IPv4IPv4
共享池,事务模式aws-[INDEX]-[REGION].pooler.supabase.com:6543IPv4IPv4IPv4
专用池,事务模式db.[PROJECT-REF].supabase.co:6543-IPv6IPv4

共享 pooler 主机中的 [INDEX] 是 pooler 集群索引,不是区域名称的一部分。一个区域可能有不止一个,所以你不能从区域推断出主机。请从连接对话框中复制主机。

用户名会根据连接类型不同而不同。直接连接和专用连接池使用 postgres。共享连接池的连接使用 postgres.[PROJECT-REF]。如果通过共享连接池以自定义角色连接,用户名是 [ROLE].[PROJECT-REF]。

🌐 The username differs by connection type. Direct connections and the dedicated pooler use postgres. Shared pooler connections use postgres.[PROJECT-REF]. If you connect as a custom role through the shared pooler, the username is [ROLE].[PROJECT-REF].

这个端口会把连接路由到正确的连接池和模式。端口 5432 连接 Postgres 用于直接连接,也连接 Supavisor 用于会话模式。端口 6543 连接 PgBouncer 用于专用连接池,也连接 Supavisor 用于共享事务模式。

🌐 The port routes the connection to the right pooler and mode. Port 5432 reaches Postgres for a direct connection and Supavisor for session mode. Port 6543 reaches PgBouncer for the dedicated pooler and Supavisor for shared transaction mode.

要通过 IPv4 连接,你有两种选择。共享连接池在每个计划中都是仅支持 IPv4 的,无论是在会话模式还是事务模式下。或者,你可以为你的项目添加 IPv4 附加组件,这样直接连接和专用连接池就可以通过 IPv4 而不是 IPv6 访问。

🌐 To connect over IPv4, you have two options. The shared pooler is IPv4-only on every plan, in both session and transaction mode. Alternatively, add the IPv4 add-on to your project, which makes the direct connection and the dedicated pooler reachable over IPv4 instead of IPv6.

配置你的客户端 #

🌐 Configure your client

仅有连接字符串是不够的。你的连接库会保留它自己的一组连接,和 Supabase 运行的连接池是分开的,而且它的默认设置假设是持续存在的后台。

🌐 A connection string on its own isn't enough. Your connection library keeps its own pool of connections, separate from the poolers Supabase runs, and its defaults assume a persistent backend.

在无服务器函数中:

🌐 In a serverless function:

  1. 在模块级别只创建一次客户端,而不是每次请求都创建。
  2. 将连接池设置为 1 个连接。客户端在这个已预热的实例中的每次调用都会共享,所以这是限制实例而不是请求。
  3. 关闭预处理语句,事务模式 不支持它。
  4. 将 SSL 设置为 require,这样驱动在没有加密的情况下就会拒绝连接。
import postgres from 'postgres'
export const sql = postgres(process.env.DATABASE_URL, {
max: 1,
prepare: false,
ssl: 'require',
})

本节的其余部分会解释每个设置,以及对于除了 Postgres.js 之外的驱动会有什么变化。

🌐 The rest of this section explains each setting, and what changes for a driver other than Postgres.js.

应用端池大小 #

🌐 Application-side pool size

库的默认设置对于无服务器来说太高了。Postgres.js 默认是 10 个连接。这意味着每个保持活跃的函数实例都有 10 个连接,而你无法控制活跃实例的数量。几十个实例就足以耗尽连接池。

🌐 Library defaults are too high for serverless. Postgres.js defaults to 10 connections. That is 10 connections for every warm instance of your function, and the number of warm instances isn't something you control. A few dozen instances is enough to exhaust the pool.

只有在你有证据表明单个实例上的并发调用正在排队等待连接时,才把连接池提高到超过 1。

🌐 Raise the pool above 1 only when you have evidence that concurrent invocations on one instance are queuing for the connection.

想了解更多关于应用端池大小的内容,请参考 Supavisor FAQ。如果你使用 Prisma,Prisma 故障排除 涵盖了等效的 connection_limit 设置。

🌐 For more on sizing an application-side pool, see the Supavisor FAQ. If you use Prisma, Prisma troubleshooting covers the equivalent connection_limit setting.

事务模式限制 #

🌐 Transaction mode limitations

事务模式 会在每次事务后将你的连接返回连接池,所以任何依赖会话状态的东西在事务之间都不会保留。有四件事会受到影响。

预处理语句不受支持,所以请关闭它们。每个驱动的操作方式都不同:

驱动设置
Postgres.js, Drizzleprepare: false
Prisma在连接字符串中使用 pgbouncer=true
asyncpgstatement_cache_size=0
JDBCprepareThreshold=0

对于 node-postgres、Psycopg 和 Rust 驱动,请参见 禁用预处理语句。

🌐 For node-postgres, Psycopg, and Rust drivers, see Disabling prepared statements.

游标 仅在单个事务内工作。with hold 游标的设计是可以超出其事务存在,但它无法在连接回到连接池后继续存在。

会话级状态在事务之间会丢失。这包括 set 和 reset、会话级建议锁、listen 和 notify 以及临时表。需要的话就在需要它们的事务里运行,或者改用会话模式或直接连接。

查询流水线不被支持:事务模式在看到一个回复完成后会立即将连接返回到连接池,即使客户端已经在该连接上排队了更多查询。

直接连接和会话模式都支持这四个,所以这些都不适用于任何一个。

🌐 Direct connections and session mode support all four, so none of this applies to either.

SSL #

🌐 SSL [#connecting-with-ssl]

尽量使用 SSL 连接,以防止窃听和中间人攻击。

🌐 Connect using SSL wherever possible, to prevent snooping and man-in-the-middle attacks.

将 SSL 设置为 require,这样驱动程序在没有加密的情况下会拒绝连接。大多数驱动程序默认是 prefer,如果加密尝试失败,会回退到以明文发送数据。在连接字符串中,这表示 sslmode=require。

🌐 Set SSL to require so the driver refuses to connect without encryption. Most drivers default to prefer, which falls back to sending your data in plaintext if the encrypted attempt fails. On a connection string, this is sslmode=require.

require 会加密连接,但不会验证服务器,所以不能防止中间人攻击。要同时进行验证和加密,可以从 Supabase 控制面板的 数据库设置 下载你的服务器根证书,然后在驱动程序中指定它。单独下载证书不会改变任何东西:必须在连接字符串中用 sslmode=verify-full 和 sslrootcert 告诉驱动程序使用它,或者在你使用的库中设置等效选项。同一部分还有一个开关,可以拒绝数据库的非 SSL 连接。

The SSL Configuration section of Database settings, with a toggle to enforce SSL on incoming connections and a Download Certificate button.

陈旧的连接 #

🌐 Stale connections

无服务器运行时会在请求之间冻结函数,这可能会导致池中的 TCP 套接字变得过时。如果你看到 CONNECT_TIMEOUT 错误或查询一直挂起直到执行限制,请参见 在无服务器函数中排查 CONNECT_TIMEOUT 或挂起的查询。

🌐 Serverless runtimes freeze a function between requests, which can leave a pooled TCP socket stale. If you see CONNECT_TIMEOUT errors or queries that hang until the execution limit, see Troubleshooting CONNECT_TIMEOUT or hanging queries in Serverless Functions.

快速入门 #

🌐 Quickstarts [#quickstarts]

每个快速入门都会将一个 ORM 或数据库 GUI 连接到你的 Supabase 数据库。

🌐 Each quickstart connects one ORM or database GUI to your Supabase database.

🌐 Related

故障排除 #

🌐 Troubleshooting