设置 Prisma ORM
在 Next.js 项目中配置并集成 Prisma ORM,以便与各种数据库交互
设置 Prisma ORM 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What is an ORM?
Welcome! In this lesson, we'll set up Prisma ORM in a Next.js project. But first, what's an ORM?
- ORM stands for Object-Relational Mapping.
- It's a technique that lets you interact with your database using your programming language's objects instead of writing raw SQL.
- Think of it as a translator between your code (e.g., JavaScript objects) and your database (e.g., SQL tables).
Why Choose Prisma?
Prisma is a modern ORM that's popular with Next.js for good reasons:
- Type Safety: It generates a type-safe client, preventing many runtime errors.
- Developer Experience: Intuitive API, powerful migrations, and automatic code completion.
- Modern Stack: Designed for TypeScript and modern JavaScript, fitting perfectly with Next.js.
- Database Support: Works with PostgreSQL, MySQL, SQLite, SQL Server, and MongoDB.
Installing Prisma
Let's start by adding Prisma to your Next.js project. You'll need two main packages:
prisma: The Prisma CLI (Command Line Interface) for development tasks.@prisma/client: The Prisma Client library for interacting with your database in code.
Run this command in your project's root:
npm install prisma @prisma/clientInitialize Prisma
After installation, you need to initialize Prisma in your project. This command sets up the basic Prisma structure, including the prisma/schema.prisma file.
It also creates a .env file to hold your database connection string.
npx prisma initConnect Your Database
The .env file created by prisma init contains a DATABASE_URL variable. This is where you tell Prisma how to connect to your database.
For local development, SQLite is often used for simplicity. For production, you might use PostgreSQL or MySQL.
# .env
DATABASE_URL="postgresql://user:password@host:port/database?schema=public"
# Example for SQLite (local file)
# DATABASE_URL="file:./dev.db"The Prisma Schema File
Your prisma/schema.prisma file is the heart of your Prisma setup. It defines three key blocks:
datasource: Specifies your database provider (e.g.,postgresql,sqlite).generator: Configures the Prisma Client (usuallyprisma-client-js).model: Defines your database tables (models) and their fields.
Defining Your First Model
Let's define a simple User model in your prisma/schema.prisma file. This model will represent a table in your database.
id: Unique identifier, auto-incrementing.email: User's email, must be unique.name: User's name, optional.
// prisma/schema.prisma
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}Generating Prisma Client
After defining or changing your models in schema.prisma, you must generate the Prisma Client. This command reads your schema and creates the type-safe client library.
This client is what you'll import and use in your Next.js application to interact with your database.
npx prisma generateApplying Migrations
To create or update your database tables based on your schema.prisma, you use migrations. The migrate dev command:
- Compares your schema to the database.
- Generates SQL migration files.
- Applies these migrations to your database.
It also generates the Prisma Client automatically after migration.
npx prisma migrate dev --name initUsing Prisma Client
Once Prisma is set up and generated, you can use the PrismaClient in your Next.js server components or API routes to perform database operations. Here's a basic example:
import { PrismaClient } from '@prisma/client';
async function main() {
const prisma = new PrismaClient();
console.log("Prisma Client successfully initialized!");
// In a real app, you'd perform database operations:
// const users = await prisma.user.findMany();
// console.log(users);
await prisma.$disconnect();
console.log("Prisma Client disconnected.");
}
main().catch(console.error);Quick Check: Prisma Commands
You've learned about several key Prisma CLI commands. Which command is used to generate the type-safe Prisma Client after you've modified your schema.prisma file?
Recap: Setting Up Prisma
Great job! You've learned the essential steps to integrate Prisma ORM into your Next.js project:
- Installed Prisma CLI and client.
- Initialized Prisma and configured your database URL.
- Defined data models in
schema.prisma. - Generated the Prisma Client.
- Applied migrations to sync your schema with the database.
- Understood how to instantiate and use
PrismaClient.
Next, we'll dive into performing CRUD operations with Prisma!
常见问题解答
「设置 Prisma ORM」课时是免费的吗?
是的 — 「设置 Prisma ORM」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。
「设置 Prisma ORM」这节课中我会学到什么?
在 Next.js 项目中配置并集成 Prisma ORM,以便与各种数据库交互 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「设置 Prisma ORM」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 设置 Prisma ORM
- 使用服务器操作实现 CRUD
- 数据库架构迁移
- 数据库填充与连接池