Skip to main content

关系数据库(TypeScript 和 Prisma Postgres)

了解如何从头开始使用 Prisma Postgres 数据库创建新的 TypeScript 项目。本教程向你介绍 Prisma CLIPrisma 客户端Prisma 迁移,并涵盖以下工作流程:

¥Learn how to create a new TypeScript project with a Prisma Postgres database from scratch. This tutorial introduces you to the Prisma CLI, Prisma Client, and Prisma Migrate and covers the following workflows:

先决条件

¥Prerequisites

要成功完成本教程,你需要:

¥To successfully complete this tutorial, you need:

创建项目设置

¥Create project setup

创建一个项目目录并导航到它:

¥Create a project directory and navigate into it:

mkdir hello-prisma
cd hello-prisma

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

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

npm init -y
npm install prisma typescript tsx @types/node --save-dev

这会创建一个 package.json,并为你的 TypeScript 应用进行初始设置。

¥This creates a package.json with an initial setup for your TypeScript app.

接下来,初始化 TypeScript:

¥Next, initialize TypeScript:

npx tsc --init

你现在可以通过添加 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 --db --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.

  • output 设置为自定义位置。

    ¥Sets the output to a custom location.

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

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

在下一节中,你将了解如何将 Prisma Postgres 数据库连接到你刚刚在文件系统上创建的项目。

¥In the next section, you'll learn how to connect your Prisma Postgres database to the project you just created on your file system.