DEV Community

Harsh Mishra
Harsh Mishra

Posted on

Prisma.js with MySQL

Complete Guide to Prisma.js with MySQL: A Comprehensive Tutorial

Prisma.js is a modern database toolkit that simplifies working with databases in Node.js and TypeScript applications. It offers a type-safe and intuitive way to interact with databases, making development faster and less error-prone. This comprehensive guide will cover everything you need to know about Prisma.js with MySQL, from installation and setup to advanced database queries, migrations, and best practices.


Table of Contents

  1. Introduction to Prisma.js
  2. Why Use Prisma with MySQL?
  3. Setting Up Prisma with MySQL
  4. Understanding Prisma Schema
  5. Running Database Migrations
  6. CRUD Operations with Prisma Client
  7. Advanced Queries in Prisma
  8. Using Prisma with Express.js
  9. Working with Relations
  10. Seeding the Database
  11. Using Transactions
  12. Performance Optimization
  13. Error Handling in Prisma
  14. Deployment Best Practices
  15. Conclusion

1. Introduction to Prisma.js

Prisma is an open-source ORM (Object-Relational Mapper) that simplifies database access in Node.js and TypeScript applications. It provides:

  • Prisma Client: Auto-generated and type-safe database queries.
  • Prisma Migrate: A powerful migration tool for database schema changes.
  • Prisma Studio: A GUI for viewing and managing database records.

Prisma supports MySQL, PostgreSQL, SQLite, SQL Server, MongoDB, and CockroachDB.


2. Why Use Prisma with MySQL?

Prisma is an excellent choice for working with MySQL because it offers:

Type Safety: Auto-generated TypeScript types for database models.

Readable Queries: Uses a simple, declarative syntax.

Auto Migrations: Handles schema changes effortlessly.

Performance Optimization: Optimized queries and caching.

Database Agnostic: Easily switch between databases.


3. Setting Up Prisma with MySQL

Step 1: Install Node.js and MySQL

Make sure you have Node.js installed. Install MySQL and create a database:

CREATE DATABASE mydatabase;
Enter fullscreen mode Exit fullscreen mode

Step 2: Initialize a Node.js Project

mkdir my-prisma-app
cd my-prisma-app
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 3: Install Prisma and MySQL Client

npm install prisma --save-dev
npm install @prisma/client mysql2
Enter fullscreen mode Exit fullscreen mode

Step 4: Initialize Prisma

npx prisma init
Enter fullscreen mode Exit fullscreen mode

This creates a prisma folder with a schema.prisma file.

Step 5: Configure Prisma for MySQL

Edit prisma/schema.prisma:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}
Enter fullscreen mode Exit fullscreen mode

Step 6: Set Up Environment Variables

Edit .env:

DATABASE_URL="mysql://root:password@localhost:3306/mydatabase"
Enter fullscreen mode Exit fullscreen mode

4. Understanding Prisma Schema

The schema.prisma file defines the database structure.

Example schema for Users and Posts:

model User {
  id       Int      @id @default(autoincrement())
  name     String
  email    String   @unique
  posts    Post[]
}

model Post {
  id       Int      @id @default(autoincrement())
  title    String
  content  String?
  author   User     @relation(fields: [userId], references: [id])
  userId   Int
}
Enter fullscreen mode Exit fullscreen mode
  • @id: Defines a primary key.
  • @default(autoincrement()): Auto-increment ID.
  • @unique: Ensures unique values.
  • @relation: Defines foreign key relationships.

5. Running Database Migrations

Generate migration files:

npx prisma migrate dev --name init
Enter fullscreen mode Exit fullscreen mode

Apply migrations:

npx prisma migrate deploy
Enter fullscreen mode Exit fullscreen mode

Check database models:

npx prisma db push
Enter fullscreen mode Exit fullscreen mode

6. CRUD Operations with Prisma Client

1. Import Prisma Client

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
Enter fullscreen mode Exit fullscreen mode

2. Create a User

const newUser = await prisma.user.create({
  data: {
    name: "John Doe",
    email: "john@example.com"
  }
});
console.log(newUser);
Enter fullscreen mode Exit fullscreen mode

3. Read Users

const users = await prisma.user.findMany();
console.log(users);
Enter fullscreen mode Exit fullscreen mode

4. Update a User

const updatedUser = await prisma.user.update({
  where: { id: 1 },
  data: { name: "Jane Doe" }
});
console.log(updatedUser);
Enter fullscreen mode Exit fullscreen mode

5. Delete a User

await prisma.user.delete({
  where: { id: 1 }
});
Enter fullscreen mode Exit fullscreen mode

7. Advanced Queries in Prisma

Filtering and Sorting

const users = await prisma.user.findMany({
  where: { name: { contains: "John" } },
  orderBy: { name: "asc" }
});
Enter fullscreen mode Exit fullscreen mode

Pagination

const users = await prisma.user.findMany({
  skip: 10,
  take: 5
});
Enter fullscreen mode Exit fullscreen mode

Raw SQL Queries

const result = await prisma.$queryRaw`SELECT * FROM User`;
console.log(result);
Enter fullscreen mode Exit fullscreen mode

8. Using Prisma with Express.js

Install Express

npm install express
Enter fullscreen mode Exit fullscreen mode

Create an Express API

const express = require('express');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
const app = express();
app.use(express.json());

app.get('/users', async (req, res) => {
  const users = await prisma.user.findMany();
  res.json(users);
});

app.listen(3000, () => console.log('Server running on port 3000'));
Enter fullscreen mode Exit fullscreen mode

9. Working with Relations

Prisma supports one-to-one, one-to-many, and many-to-many relations.

  • One-to-Many (User → Posts)
  • Many-to-Many (Users ↔ Groups)

Example many-to-many relationship:

model User {
  id    Int    @id @default(autoincrement())
  name  String
  groups Group[] @relation("UserGroups")
}

model Group {
  id    Int    @id @default(autoincrement())
  name  String
  users User[] @relation("UserGroups")
}
Enter fullscreen mode Exit fullscreen mode

10. Seeding the Database

Create prisma/seed.js:

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function main() {
  await prisma.user.createMany({
    data: [{ name: "Alice" }, { name: "Bob" }]
  });
}

main().catch(console.error).finally(() => prisma.$disconnect());
Enter fullscreen mode Exit fullscreen mode

Run the seed script:

node prisma/seed.js
Enter fullscreen mode Exit fullscreen mode

Conclusion

Prisma.js with MySQL offers a type-safe, intuitive, and efficient way to manage databases. From migrations and CRUD operations to advanced queries and API integration, Prisma simplifies database management while improving performance and developer experience. 🚀

Top comments (0)