Skip to content
On this page

Prisma Client

Prisma Client 是一个自动生成的、类型安全的数据库客户端,用于从数据库读取和写入数据。它是 Prisma 的主要 API。

生成 Prisma Client

每次修改 schema 后都需要重新生成客户端:

bash
npx prisma generate

初始化 Prisma Client

typescript
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

基础 CRUD 操作

查询数据

typescript
// 获取所有用户
const allUsers = await prisma.user.findMany()

// 根据 ID 查询用户
const user = await prisma.user.findUnique({
  where: { id: 1 }
})

// 条件查询
const users = await prisma.user.findMany({
  where: {
    email: {
      contains: 'example.com'
    }
  }
})

创建数据

typescript
const newUser = await prisma.user.create({
  data: {
    email: 'alice@example.com',
    name: 'Alice'
  }
})

更新数据

typescript
const updatedUser = await prisma.user.update({
  where: { id: 1 },
  data: {
    name: 'Alice Smith'
  }
})

删除数据

typescript
const deletedUser = await prisma.user.delete({
  where: { id: 1 }
})

关系查询

包含关联数据

typescript
const userWithPosts = await prisma.user.findUnique({
  where: { id: 1 },
  include: {
    posts: true
  }
})

嵌套写入操作

typescript
const userWithPosts = await prisma.user.create({
  data: {
    email: 'bob@example.com',
    name: 'Bob',
    posts: {
      create: [
        { title: 'First Post' },
        { title: 'Second Post' }
      ]
    }
  },
  include: {
    posts: true
  }
})

高级查询功能

排序和分页

typescript
const paginatedUsers = await prisma.user.findMany({
  skip: 5,           // 跳过前5条记录
  take: 10,          // 获取10条记录
  orderBy: {
    email: 'asc'     // 按邮箱升序排列
  }
})

聚合查询

typescript
const userCount = await prisma.user.count()

const groupedResult = await prisma.user.groupBy({
  by: ['role'],
  _count: {
    _all: true
  }
})

事务处理

typescript
const result = await prisma.$transaction([
  prisma.user.update({
    where: { id: 1 },
    data: { balance: { decrement: 100 } }
  }),
  prisma.user.update({
    where: { id: 2 },
    data: { balance: { increment: 100 } }
  })
])

原生 SQL 查询

对于复杂查询,可以使用原生 SQL:

typescript
const rawQueryResult = await prisma.$queryRaw`
  SELECT * FROM User WHERE age > ${age}
`

错误处理

typescript
try {
  const user = await prisma.user.findUnique({
    where: { id: 999999 }
  })
} catch (error) {
  if (error instanceof Prisma.PrismaClientKnownRequestError) {
    // 处理 Prisma 特定错误
  }
}

连接管理

typescript
// 关闭连接
await prisma.$disconnect()

总结

Prisma Client 提供了一个直观、类型安全的 API 来与数据库交互,大大简化了数据库操作。