Skip to main content

Prisma Client for Database Queries

5. Prisma Client for Database Queries

Prisma Client is an auto-generated, type-safe client that allows us to interact with the database using our defined models.

Generating the Client

After defining models or making schema changes, we regenerate Prisma Client:

npx prisma generate

Using Prisma Client in Code

Here’s an example of creating a new user and querying all users:

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

async function main() {
// Creating a new user
const newUser = await prisma.user.create({
data: {
email: 'newuser@example.com',
password: 'hashedpassword',
name: 'New User'
},
});
console.log('User created:', newUser);

// Retrieving all users
const allUsers = await prisma.user.findMany();
console.log('All users:', allUsers);
}

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

Why Prisma Client?

Using Prisma Client offers:

  • Type Safety: Since the client is generated based on the schema, it ensures type safety for all queries.
  • Readability: Prisma’s query syntax is declarative, making code easy to read and maintain.