关系数据库(TypeScript 和 Prisma Postgres)
了解如何从头开始使用 Prisma Postgres 数据库创建新的 TypeScript 项目。本教程向你介绍 Prisma CLI、Prisma 客户端 和 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:
-
从头开始在本地机器上创建 TypeScript 项目
¥Creating a TypeScript project on your local machine from scratch
-
创建 Prisma Postgres 数据库
¥Creating a Prisma Postgres database
-
架构迁移和查询(通过 Prisma ORM)
¥Schema migrations and queries (via Prisma ORM)
-
连接池和缓存(通过 Prisma 加速)
¥Connection pooling and caching (via Prisma Accelerate)
先决条件
¥Prerequisites
要成功完成本教程,你需要:
¥To successfully complete this tutorial, you need:
-
(PDP) 账户
¥a (PDP) account
-
Node.js 安装在你的机器上(请参阅 系统要求 了解官方支持的版本)(请参阅 系统要求 了解官方支持的版本)
¥Node.js installed on your machine (see system requirements for officially supported versions) (see system requirements for officially supported versions)
创建项目设置
¥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 calledschema.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.