Skip to main content

使用 JavaScript 和 PostgreSQL 连接现有数据库

连接你的数据库

¥Connecting your database

要连接数据库,你需要将 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 中定义的 通过环境变量设置

¥In this case, the url is set via an environment variable which is defined in .env:

.env
DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"

你现在需要调整连接 URL 以指向你自己的数据库。

¥You now need to adjust the connection URL to point to your own database.

Connection URL

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

¥The format of the connection URL for your database depends on the database you use. For PostgreSQL, it looks as follows (the parts spelled all-uppercased are placeholders for your specific connection details):

postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA

注意:大多数情况下,你可以使用 postgres://postgresql:// URI scheme designators interchangeably - 但是,根据数据库的托管方式,你可能需要具体说明。

¥Note: In most cases, you can use the postgres:// and postgresql:// URI scheme designators interchangeably - however, depending on how your database is hosted, you might need to be specific.

如果你不确定为 PostgreSQL 连接 URL 的 schema 参数提供什么,你可以忽略它。在这种情况下,将使用默认模式名称 public

¥If you're unsure what to provide for the schema parameter for a PostgreSQL connection URL, you can probably omit it. In that case, the default schema name public will be used.

例如,对于 Heroku 上托管的 PostgreSQL 数据库,连接 URL 可能类似于以下内容:

¥As an example, for a PostgreSQL database hosted on Heroku, the connection URL might look similar to this:

.env
DATABASE_URL="postgresql://opnmyfngbknppm:XXX@ec2-46-137-91-216.eu-west-1.compute.amazonaws.com:5432/d50rgmkqi2ipus?schema=hello-prisma"

在 macOS 上本地运行 PostgreSQL 时,你的用户和密码以及数据库名称通常对应于操作系统的当前用户,例如 假设用户名为 janedoe

¥When running PostgreSQL locally on macOS, your user and password as well as the database name typically correspond to the current user of your OS, e.g. assuming the user is called janedoe:

.env
DATABASE_URL="postgresql://janedoe:janedoe@localhost:5432/janedoe?schema=hello-prisma"