Prisma is a modern database toolkit that simplifies database access with an intuitive ORM. This guide covers setting up Prisma with MySQL and performing CRUD (Create, Read, Update, Delete) operations.
- Node.js installed
- MySQL installed and running
- A MySQL database created
mkdir prisma-mysql-crud
cd prisma-mysql-crud
npm init -ynpm install @prisma/client
npm install --save-dev prismanpx prisma initThis creates a prisma folder and a .env file for database configuration.
Edit .env file:
DATABASE_URL="mysql://user:password@localhost:3306/dbname"Replace user, password, and dbname with your actual database credentials.
Edit prisma/schema.prisma:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}Run the migration command:
npx prisma migrate dev --name initCreate a file prismaClient.js:
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
export default prisma;const user = await prisma.user.create({
data: {
name: "John Doe",
email: "john@example.com",
},
});
console.log(user);const users = await prisma.user.findMany();
console.log(users);const updatedUser = await prisma.user.update({
where: { email: "john@example.com" },
data: { name: "John Updated" },
});
console.log(updatedUser);const deletedUser = await prisma.user.delete({
where: { email: "john@example.com" },
});
console.log(deletedUser);This guide covered setting up Prisma with MySQL and performing CRUD operations. Prisma makes database management easier with an intuitive API and type safety.