数据库填充与连接池
使用可靠的初始数据填充数据库,并配置 Prisma 连接池,让您的 Next.js 应用在高负载下依然快速稳定。
数据库填充与连接池 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Seed a Database?
Seeding fills your database with predictable starter data: admin users, demo records, lookup tables. It lets every developer and every CI run start from the same known state.
Without seeds, manual data entry makes tests flaky and onboarding slow.
The Prisma Seed Script
Prisma runs a seed file you point it at. Create prisma/seed.ts and register it in package.json under the prisma.seed key so prisma db seed knows what to execute.
{
"prisma": {
"seed": "ts-node prisma/seed.ts"
}
}Writing Seed Logic
Inside the seed file you instantiate the client and create records. Wrap it in an async function and disconnect when finished.
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
await prisma.user.create({
data: { email: 'admin@app.com', name: 'Admin' }
});
}
main().finally(() => prisma.$disconnect());Idempotent Seeds with upsert
Running a seed twice should not create duplicates. Use upsert so a record is created if missing and updated if it already exists.
await prisma.user.upsert({
where: { email: 'admin@app.com' },
update: {},
create: { email: 'admin@app.com', name: 'Admin' }
});Bulk Seeding
To insert many rows efficiently, use createMany. The skipDuplicates option avoids errors on unique conflicts.
await prisma.tag.createMany({
data: [
{ name: 'news' },
{ name: 'sports' },
{ name: 'tech' }
],
skipDuplicates: true
});Running the Seed
Trigger the script from the CLI. Prisma also runs it automatically after prisma migrate reset, giving you a clean reseeded database.
npx prisma db seedThe Connection Problem in Serverless
Next.js on Vercel runs serverless functions. Each invocation can open a fresh DB connection, and under load you quickly exhaust the database connection limit.
Connection pooling solves this by reusing a fixed set of connections.
Reusing the Prisma Client
In development, hot reload can spawn many clients. Store a single instance on globalThis so only one client exists per process.
import { PrismaClient } from '@prisma/client';
const g = globalThis as unknown as { prisma?: PrismaClient };
export const prisma = g.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') g.prisma = prisma;Pooling with a Connection URL
Use a pooler such as PgBouncer or Prisma Accelerate. Point your DATABASE_URL at the pooled endpoint and add ?pgbouncer=true so Prisma disables prepared statements that PgBouncer cannot share.
DATABASE_URL="postgresql://user:pass@host:6543/db?pgbouncer=true&connection_limit=1"Direct URL for Migrations
Pooled connections cannot run migrations. Add a directUrl in your schema that bypasses the pooler so prisma migrate works.
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}Best Practices
Keep your data layer healthy:
- Make seeds idempotent with upsert
- Reuse a single client instance
- Use a pooler in serverless environments
- Keep a separate direct URL for migrations
Quick Check
Test what you learned about pooling.
Recap
You learned to seed and pool your database:
- Configure
prisma.seedand write idempotent seeds withupsert - Bulk insert with
createMany - Reuse a single Prisma client to avoid leaks
- Use a pooled
DATABASE_URLplus adirectUrlfor migrations
Now your database starts in a known state and scales safely.
常见问题解答
「数据库填充与连接池」课时是免费的吗?
是的 — 「数据库填充与连接池」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。
「数据库填充与连接池」这节课中我会学到什么?
使用可靠的初始数据填充数据库,并配置 Prisma 连接池,让您的 Next.js 应用在高负载下依然快速稳定。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「数据库填充与连接池」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 设置 Prisma ORM
- 使用服务器操作实现 CRUD
- 数据库架构迁移
- 数据库填充与连接池