Skip to main content

实例化 Prisma 客户端

以下示例演示了如何从 默认路径 导入并实例化 生成的客户端

¥The following example demonstrates how to import and instantiate your generated client from the default path:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()
提示

你可以使用 构造函数参数 进一步自定义 PrismaClient — 例如,设置 日志记录级别事务选项 或自定义 格式错误

¥You can further customize PrismaClient with constructor parameters — for example, set logging levels, transaction options or customize error formatting.

PrismaClient 实例的数量很重要

¥The number of PrismaClient instances matters

你的应用通常应该只创建一个 PrismaClient 实例。如何实现这一点取决于你是在 长时间运行的应用 还是 无服务器环境 中使用 Prisma ORM。

¥Your application should generally only create one instance of PrismaClient. How to achieve this depends on whether you are using Prisma ORM in a long-running application or in a serverless environment .

原因是 PrismaClient 的每个实例都管理一个连接池,这意味着大量的客户端可以耗尽数据库连接限制。这适用于所有数据库连接器。

¥The reason for this is that each instance of PrismaClient manages a connection pool, which means that a large number of clients can exhaust the database connection limit. This applies to all database connectors.

如果你使用 MongoDB 连接器,连接由 MongoDB 驱动程序连接池管理。如果你使用关系数据库连接器,连接由 Prisma ORM 的 连接池 管理。PrismaClient 的每个实例都会创建自己的池。

¥If you use the MongoDB connector, connections are managed by the MongoDB driver connection pool. If you use a relational database connector, connections are managed by Prisma ORM's connection pool. Each instance of PrismaClient creates its own pool.

  1. 每个客户端创建自己的 查询引擎 实例。

    ¥Each client creates its own instance of the query engine.

  2. 每个查询引擎都会创建一个 连接池,其默认池大小为:

    ¥Each query engine creates a connection pool with a default pool size of:

  3. 太多连接可能会开始减慢数据库速度并最终导致错误,例如:

    ¥Too many connections may start to slow down your database and eventually lead to errors such as:

    Error in connector: Error querying the database: db error: FATAL: sorry, too many clients already
    at PrismaClientFetcher.request