Skip to main content

使用 TypeScript 和 PostgreSQL 连接数据库

要连接数据库,你需要将 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"
info

我们建议将 .env 添加到 .gitignore 文件中,以防止提交环境变量。

¥We recommend adding .env to your .gitignore file to prevent committing your environment variables.

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

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

你的数据库的 连接 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

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

¥Here's a short explanation of each component:

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

    ¥USER: The name of your database user

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

    ¥PASSWORD: The password for your database user

  • HOST:你的主机名(对于本地环境,为 localhost

    ¥HOST: The name of your host name (for the local environment, it is localhost)

  • PORT:数据库服务器运行的端口(对于 PostgreSQL,通常为 5432

    ¥PORT: The port where your database server is running (typically 5432 for PostgreSQL)

  • DATABASEdatabase 的名字

    ¥DATABASE: The name of the database

  • SCHEMA:数据库里面 schema 的名字

    ¥SCHEMA: The name of the schema inside the database

如果你不确定为 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 数据库,连接网址 可能类似于以下内容:

¥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"