Writing and Reading Data: CRUD Operations Part 1
To communicate with your database, instantiate the Prisma Client in your application files. Let us explore the basic methods for inserting and querying records.
1. Initializing Prisma Client
First, install the client package:
# Install Prisma Client runtime package
npm install @prisma/clientGenerate the client code based on your current schema file:
# Compile and generate client typings
npx prisma generateCreate a singleton client instance inside src/lib/db.ts:
// src/lib/db.ts
import { PrismaClient } from "@prisma/client";
export const db = new PrismaClient();2. Inserting Records (Create)
Prisma provides two primary methods for inserting records:
A. Inserting a Single Record
const newUser = await db.user.create({
data: {
email: "alice@example.com",
name: "Alice",
},
});B. Bulk Inserting Multiple Records
Use createMany to insert multiple rows in a single database transaction (supported on PostgreSQL and MySQL):
const users = await db.user.createMany({
data: [
{ email: "bob@example.com", name: "Bob" },
{ email: "charlie@example.com", name: "Charlie" },
],
skipDuplicates: true, // Ignore conflicts
});3. Querying Records (Read)
Prisma Client provides query helpers to retrieve data:
A. Finding a Unique Record
Use findUnique to query a row by its primary key or a column marked with the @unique constraint:
const user = await db.user.findUnique({
where: {
email: "alice@example.com",
},
});B. Finding the First Matching Record
Use findFirst to query the first row that matches your filter conditions:
const user = await db.user.findFirst({
where: {
name: "Alice",
},
});C. Fetching All Matching Records
Use findMany to retrieve a list of all rows that match your criteria:
const activeUsers = await db.user.findMany();