Skip to main content

使用 TypeScript 和 PlanetScale 连接现有数据库

连接你的数据库

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

你还需要在 datasource 块中添加 将关系模式类型设置为 prisma

¥You will also need to set the relation mode type to prisma in the datasource block:

schema.prisma
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
relationMode = "prisma"
}

url.env 中定义的 通过环境变量设置

¥The url is set via an environment variable which is defined in .env:

.env
DATABASE_URL="mysql://janedoe:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict"

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

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

Connection URL

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

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

mysql://USER:PASSWORD@HOST:PORT/DATABASE

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

¥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:数据库服务器运行的端口(对于 MySQL 通常为 3306

    ¥PORT: The port where your database server is running (typically 3306 for MySQL)

  • DATABASEdatabase 的名字

    ¥DATABASE: The name of the database

对于由 PlanetScale 托管的数据库,连接网址 看起来类似于:

¥For a database hosted with PlanetScale, the connection URL looks similar to this:

.env
DATABASE_URL="mysql://myusername:mypassword@server.us-east-2.psdb.cloud/mydb?sslaccept=strict"

通过转到分支的概述页面并选择 'Connect' 下拉列表,可以从你的 PlanetScale 账户找到给定数据库分支的连接 URL。在 '密码' 部分中,生成新密码并选择 'Prisma' 以获取连接 URL 的 Prisma 格式。

¥The connection URL for a given database branch can be found from your PlanetScale account by going to the overview page for the branch and selecting the 'Connect' dropdown. In the 'Passwords' section, generate a new password and select 'Prisma' to get the Prisma format for the connection URL.

Alternative method: connecting using the PlanetScale CLI

或者,你可以使用 PlanetScale CLI 连接到 PlanetScale 数据库服务器,并使用本地连接 URL。在这种情况下,连接 URL 将如下所示:

¥Alternatively, you can connect to your PlanetScale database server using the PlanetScale CLI, and use a local connection URL. In this case the connection URL will look like this:

.env
DATABASE_URL="mysql://root@localhost:PORT/mydb"

要连接到你的分支,请使用以下命令:

¥To connect to your branch, use the following command:

pscale connect prisma-test branchname --port PORT

如果你使用默认端口 3306,则可以省略 --port 标志。

¥The --port flag can be omitted if you are using the default port 3306.