Skip to main content

关系数据库(JavaScript 和 PlanetScale)

了解如何通过将 Prisma ORM 连接到数据库并生成用于数据库访问的 Prisma 客户端,从头开始创建新的 Node.js 或 TypeScript 项目。以下教程向你介绍 Prisma CLIPrisma 客户端Prisma 迁移

¥Learn how to create a new Node.js or TypeScript project from scratch by connecting Prisma ORM to your database and generating a Prisma Client for database access. The following tutorial introduces you to the Prisma CLI, Prisma Client, and Prisma Migrate.

先决条件

¥Prerequisites

为了成功完成本指南,你需要:

¥In order to successfully complete this guide, you need:

warning

本教程还假设你可以推送到数据库的 main 分支。如果你的 main 分支已升级到生产环境,请勿执行此操作。

¥This tutorial will also assume that you can push to the main branch of your database. Do not do this if your main branch has been promoted to production.

接下来,初始化 Node.js 项目并将 Prisma CLI 添加为开发依赖:

¥Next, initialize a Node.js project and add the Prisma CLI as a development dependency to it:

npm init -y
npm install prisma --save-dev

这将创建一个带有 Node.js 应用初始设置的 package.json

¥This creates a package.json with an initial setup for a Node.js app.

信息

请参阅 安装说明 了解如何使用不同的包管理器安装 Prisma。

¥See installation instructions to learn how to install Prisma using a different package manager.

你现在可以通过添加 npx 前缀来调用 Prisma CLI:

¥You can now invoke the Prisma CLI by prefixing it with npx:

npx prisma

接下来,使用以下命令创建 Prisma 模式 文件来设置 Prisma ORM 项目:

¥Next, set up your Prisma ORM project by creating your Prisma Schema file with the following command:

npx prisma init --datasource-provider mysql --output ../generated/prisma

此命令执行以下几项操作:

¥This command does a few things:

  • 创建一个名为 prisma 的新目录,其中包含一个名为 schema.prisma 的文件,该文件包含 Prisma Schema、数据库连接变量和模式模型。

    ¥Creates a new directory called prisma that contains a file called schema.prisma, which contains the Prisma Schema with your database connection variable and schema models.

  • 分别将 datasource 设置为 MySQL,并将输出设置为自定义位置。

    ¥Sets the datasource to MySQL and the output to a custom location, respectively.

  • 在项目根目录中创建 .env 文件,用于定义环境变量(例如数据库连接)。

    ¥Creates the .env file in the root directory of the project, which is used for defining environment variables (such as your database connection)

请注意,prisma init 创建的默认架构使用 PostgreSQL 作为 provider。如果你未使用 datasource-provider 选项指定提供程序,则需要编辑 datasource 块以使用 mysql 提供程序:

¥Note that the default schema created by prisma init uses PostgreSQL as the provider. If you didn't specify a provider with the datasource-provider option, you need to edit the datasource block to use the mysql provider instead:

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