Prisma 클라이언트를 사용한 CRUD 작업
형식 안전성을 갖춘 Prisma 클라이언트를 사용하여 생성, 조회, 수정, 삭제 작업을 수행합니다.
Prisma 클라이언트를 사용한 CRUD 작업은(는) CoddyKit의 무료 Next.js 15 Fullstack Web Apps 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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
dataobject. - 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
whereclause to identify the record(s) to update. - A
dataobject 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()orfindFirst()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 클라이언트를 사용한 CRUD 작업” 강의는 무료인가요?
네 — “Prisma 클라이언트를 사용한 CRUD 작업” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack Web Apps 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“Prisma 클라이언트를 사용한 CRUD 작업”에서 뭘 배우나요?
형식 안전성을 갖춘 Prisma 클라이언트를 사용하여 생성, 조회, 수정, 삭제 작업을 수행합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack Web Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Next.js 15 Fullstack Web Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack Web Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“Prisma 클라이언트를 사용한 CRUD 작업” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Next.js 15 Fullstack Web Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Next.js 15 Fullstack Web Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Prisma ORM 소개
- Prisma 스키마 설계와 마이그레이션
- Prisma 클라이언트를 사용한 CRUD 작업
- Prisma의 관계와 고급 질의