关系数据库(JavaScript 和 CockroachDB)
了解如何通过将 Prisma ORM 连接到数据库并生成用于数据库访问的 Prisma 客户端,从头开始创建新的 Node.js 或 TypeScript 项目。以下教程向你介绍 Prisma CLI、Prisma 客户端 和 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:
-
Node.js 安装在你的机器上(请参阅 系统要求 了解官方支持的版本)
¥Node.js installed on your machine (see system requirements for officially supported versions)
-
正在运行的 CockroachDB 数据库服务器
¥a CockroachDB database server running
请参阅 系统要求 了解确切的版本要求。
¥See System requirements for exact version requirements.
确保你手头有数据库 连接网址。如果你没有运行数据库服务器而只想探索 Prisma ORM,请查看 快速开始。
¥Make sure you have your database connection URL at hand. If you don't have a database server running and just want to explore Prisma ORM, check out the Quickstart.
创建项目设置
¥Create project setup
第一步,创建一个项目目录并导航到其中:
¥As a first step, create a project directory and navigate into it:
mkdir hello-prisma
cd hello-prisma
接下来,初始化 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.
你现在可以通过添加 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 postgresql --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. -
分别将
datasource
设置为 PostgreSQL,并将输出设置为自定义位置。¥Sets the
datasource
to PostgreSQL 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
块以使用 postgresql
提供程序:
¥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 postgresql
provider instead:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}