0Pricing
Next.js 15 Fullstack Web Apps · 课时

使用 Prisma Client 执行 CRUD 操作

使用类型安全的 Prisma Client 执行创建、读取、更新和删除操作。

使用 Prisma Client 执行 CRUD 操作 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to CRUD with Prisma

Welcome! In this lesson, we'll master CRUD operations using Prisma Client. CRUD stands for Create, Read, Update, and Delete – the four fundamental operations for interacting with any database.

Prisma Client provides a type-safe and intuitive way to perform these actions, making your database interactions efficient and less error-prone.

Instantiating Prisma Client

Before performing any database operations, you need to instantiate the Prisma Client. This client is automatically generated based on your schema.prisma file and connects your application to the database.

You'll typically do this once in your application's entry point or a dedicated database module.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Prisma Client initialized!');
  // Database operations go here
}

main()
  .catch(e => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Create: Adding New Data

The Create operation adds new records to your database. With Prisma, you use the create method on a model to insert data.

  • Specify the model (e.g., prisma.user).
  • Provide the data for the new record in the data object.
  • Prisma handles the SQL insertion for you!

Remember, this assumes you have a User model defined in your schema.prisma.

Create: Adding a User Record

Let's create a new User record. Notice how Prisma Client provides autocompletion for fields like email and name, ensuring type safety.

Run this example to see a new user being added.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Creating a new user...');
  const newUser = await prisma.user.create({
    data: {
      email: 'alice@example.com',
      name: 'Alice Smith',
    },
  });
  console.log('Created user:', newUser.name, 'with ID:', newUser.id);
}

main()
  .catch(e => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Read: Fetching Multiple Records

The Read operation retrieves data. To fetch multiple records, use the findMany method. You can filter results using the where clause, order them with orderBy, or limit them with take.

For example, prisma.user.findMany({ where: { name: 'Alice Smith' } }) would find all users named Alice Smith.

Read: Fetching Single Records

To fetch a single, unique record, use findUnique. This method requires a unique identifier (like an @id or @unique field in your schema) to ensure only one record is returned.

If you need to find the first record matching a non-unique condition, use findFirst. It returns null if no record is found.

Read: Users from the Database

Let's fetch all users and then find a specific user by their email using findUnique. This demonstrates how to retrieve both lists and individual items.

Run the code to see the results of these queries.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Fetching all users...');
  const allUsers = await prisma.user.findMany();
  console.log('All users:', allUsers.map(u => u.name).join(', '));

  console.log('Finding user by unique email...');
  const alice = await prisma.user.findUnique({
    where: {
      email: 'alice@example.com',
    },
  });
  if (alice) {
    console.log('Found Alice:', alice.name);
  } else {
    console.log('Alice not found.');
  }
}

main()
  .catch(e => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Update: Modifying Existing Data

The Update operation changes existing records. The update method requires two main parts:

  • A where clause to identify the record(s) to update.
  • A data object containing the fields and new values to set.

Always ensure your where clause is specific enough to avoid unintended updates!

Update: Changing a User's Name

We'll update the user 'Alice Smith' to 'Alicia Wonderland'. Notice how we target the user with their unique email and then provide the new name.

After running, you can try fetching Alice again to see the updated name.

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Updating user Alice Smith...');
  const updatedUser = await prisma.user.update({
    where: {
      email: 'alice@example.com',
    },
    data: {
      name: 'Alicia Wonderland',
    },
  });
  console.log('Updated user:', updatedUser.email, 'now named:', updatedUser.name);
}

main()
  .catch(e => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Delete: Removing Data

Finally, the Delete operation removes records from your database. The delete method, like update, requires a where clause to specify which record(s) to remove.

Be cautious with delete operations, as they are permanent! Always double-check your where condition.

CRUD Operations Check

Which Prisma Client method would you use to remove a specific user record from the database?

Recap: CRUD with Prisma

Great job! You've learned the core of database interaction using Prisma Client.

  • Create (C): Use prisma.model.create() to add new records.
  • Read (R): Use prisma.model.findMany() for lists, findUnique() or findFirst() for single records.
  • Update (U): Use prisma.model.update() to modify existing records.
  • Delete (D): Use prisma.model.delete() to remove records.

Prisma's type safety and intuitive API make these essential operations straightforward and robust in your Next.js applications.

常见问题解答

「使用 Prisma Client 执行 CRUD 操作」课时是免费的吗?

是的 — 「使用 Prisma Client 执行 CRUD 操作」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

「使用 Prisma Client 执行 CRUD 操作」这节课中我会学到什么?

使用类型安全的 Prisma Client 执行创建、读取、更新和删除操作。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack Web Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用 Prisma Client 执行 CRUD 操作」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Prisma ORM 简介
  2. Prisma 模式设计与迁移
  3. 使用 Prisma Client 执行 CRUD 操作
  4. 使用 Prisma 处理关系与高级查询
← 返回 Next.js 15 Fullstack Web Apps