Skip to main content

使用 JavaScript 和 CockroachDB 连接数据库

要连接数据库,你需要将 Prisma 架构中 datasource 块的 url 字段设置为数据库 连接网址

¥To connect your database, you need to set the url field of the datasource block in your Prisma schema to your database connection URL:

prisma/schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

url.env 中定义的 通过环境变量设置。你现在需要调整连接 URL 以指向你自己的数据库。

¥The url is set via an environment variable which is defined in .env. You now need to adjust the connection URL to point to your own database.

你的数据库的 连接 URL 的格式 取决于你使用的数据库。CockroachDB 使用 PostgreSQL 连接 URL 格式,其结构如下(全大写的部分是特定连接详细信息的占位符):

¥The format of the connection URL for your database depends on the database you use. CockroachDB uses the PostgreSQL connection URL format, which has the following structure (the parts spelled all-uppercased are placeholders for your specific connection details):

postgresql://USER:PASSWORD@HOST:PORT/DATABASE?PARAMETERS

以下是每个组件的简短说明:

¥Here's a short explanation of each component:

  • USER:你的数据库用户的名称

    ¥USER: The name of your database user

  • PASSWORD:你的数据库用户的密码

    ¥PASSWORD: The password for your database user

  • PORT:数据库服务器运行的端口。CockroachDB 的默认值是 26257

    ¥PORT: The port where your database server is running. The default for CockroachDB is 26257.

  • DATABASE:数据库名称

    ¥DATABASE: The name of the database

  • PARAMETERS:任何附加连接参数。请参阅 CockroachDB 文档 此处

    ¥PARAMETERS: Any additional connection parameters. See the CockroachDB documentation here.

对于 CockroachDB 云 上托管的 CockroachDB 无服务器Cockroach 专用 数据库,连接网址 看起来类似于:

¥For a CockroachDB Serverless or Cockroach Dedicated database hosted on CockroachDB Cloud, the connection URL looks similar to this:

.env
DATABASE_URL="postgresql://<myusername>:<mypassword>@<short-id>.<region>.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full&sslrootcert=$HOME/.postgresql/root.crt&options=--<mycluster>"

要在 CockroachDB Cloud 上查找连接字符串,请单击数据库集群概述页面上的 'Connect' 按钮,然后选择 '连接字符串' 选项卡。

¥To find your connection string on CockroachDB Cloud, click the 'Connect' button on the overview page for your database cluster, and select the 'Connection string' tab.

对于 本地托管的 CockroachDB 数据库连接网址 看起来与此类似:

¥For a CockroachDB database hosted locally, the connection URL looks similar to this:

.env
DATABASE_URL="postgresql://root@localhost:26257?sslmode=disable"

从命令行启动 CockroachDB 时,你的连接字符串将显示为欢迎文本的一部分。

¥Your connection string is displayed as part of the welcome text when starting CockroachDB from the command line.