Skip to main content

使用 JavaScript 和 MySQL 连接数据库

要连接数据库,你需要将 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="mysql://johndoe:randompassword@localhost:3306/mydb"
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 的格式 通常取决于你使用的数据库。对于 MySQL,它看起来如下(全大写的部分是特定连接详细信息的占位符):

¥The format of the connection URL for your database typically depends on the database you use. For MySQL, it looks as follows (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

例如,对于 AWS RDS 上托管的 MySQL 数据库,连接网址 可能类似于以下内容:

¥As an example, for a MySQL database hosted on AWS RDS, the connection URL might look similar to this:

.env
DATABASE_URL="mysql://johndoe:XXX@mysql–instance1.123456789012.us-east-1.rds.amazonaws.com:3306/mydb"

在本地运行 MySQL 时,你的连接 URL 通常类似于以下内容:

¥When running MySQL locally, your connection URL typically looks similar to this:

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