Skip to main content

将 Prisma Postgres 与 Drizzle ORM 结合使用

Drizzle ORM 是一个 TypeScript ORM。在本指南中,你将学习如何将 Drizzle ORM 连接到 Prisma Postgres

¥Drizzle ORM is a TypeScript ORM. In this guide, you'll learn how to connect Drizzle ORM to Prisma Postgres.

先决条件

¥Prerequisites

  • Node.js 版本 16 或更高版本

    ¥Node.js version 16 or higher

  • TypeScript 版本 5.0 或更高版本

    ¥TypeScript version 5.0 or higher

1. 创建一个新项目

¥ Create a new project

为你的项目创建一个新目录,并使用 npm 进行初始化:

¥Create a new directory for your project and initialize it with npm:

mkdir drizzle-quickstart
cd drizzle-quickstart
npm init -y

安装 TypeScript 并进行初始化:

¥Install TypeScript and initialize it:

npm install --save-dev typescript
npx tsc --init

package.json 文件中,将 type 设置为 module

¥In your package.json, set the type to module:

package.json
{
// ...
"type": "module"
// ...
}

2. 创建 Prisma Postgres 数据库

¥ Create a Prisma Postgres database

你可以使用 create-db CLI 工具创建 Prisma Postgres 数据库。按照以下步骤创建你的 Prisma Postgres 数据库:

¥You can create a Prisma Postgres database using the create-db CLI tool. Follow these steps to create your Prisma Postgres database:

npx create-db

然后 CLI 工具应输出:

¥Then the CLI tool should output:

┌  🚀 Creating a Prisma Postgres database

│ Provisioning a temporary database in us-east-1...

│ It will be automatically deleted in 24 hours, but you can claim it.

◇ Database created successfully!


● Database Connection


│ Connection String:

│ postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require


◆ Claim Your Database

│ Keep your database for free:

│ https://create-db.prisma.io/claim?CLAIM_CODE

│ Database will be deleted on 11/18/2025, 1:55:39 AM if not claimed.


创建 .env 文件,并添加输出中的连接字符串:

¥Create a .env file and add the connection string from the output:

.env
DATABASE_URL="postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require"
警告

切勿将 .env 文件提交到版本控制系统。将 .env 添加到 .gitignore 文件以确保凭据安全。

¥Never commit .env files to version control. Add .env to your .gitignore file to keep credentials secure.

创建的数据库是临时的,除非被认领,否则将在 24 小时后删除。认领操作会将数据库移动到你的 账户。访问输出中的声明 URL 以保留你的数据库。

¥The database created is temporary and will be deleted in 24 hours unless claimed. Claiming moves the database into your account. Visit the claim URL from the output to keep your database.

注意

要了解有关 create-db CLI 工具的更多信息,请参阅 create-db 文档

¥To learn more about the create-db CLI tool, see the create-db documentation.

3. 安装依赖

¥ Install dependencies

安装 Drizzle ORM 和 PostgreSQL 驱动程序:

¥Install Drizzle ORM and the PostgreSQL driver:

npm install drizzle-orm pg dotenv
npm install --save-dev drizzle-kit @types/pg tsx

软件包明细:

¥Package breakdown:

  • drizzle-orm:轻量级 TypeScript ORM

    ¥drizzle-orm: The lightweight TypeScript ORM

  • pg:适用于 Node.js 的 PostgreSQL 驱动程序

    ¥pg: PostgreSQL driver for Node.js

  • dotenv:从 .env 文件加载环境变量

    ¥dotenv: Loads environment variables from .env file

  • drizzle-kit:用于迁移和模式管理的 CLI 工具

    ¥drizzle-kit: CLI tool for migrations and schema management

  • @types/pg:pg 驱动程序的 TypeScript 类型定义

    ¥@types/pg: TypeScript type definitions for the pg driver

  • tsx:用于直接运行 .ts 文件的 TypeScript 执行引擎

    ¥tsx: TypeScript execution engine for running .ts files directly

4. 运行查询

¥ Run a query

创建 src/script.ts 文件:

¥Create a src/script.ts file:

src/script.ts
import 'dotenv/config'
import { drizzle } from 'drizzle-orm/node-postgres'
import { Pool } from 'pg'

const pool = new Pool({
connectionString: process.env.DATABASE_URL,
})

const db = drizzle({ client: pool })

async function main() {
const result = await db.execute('select 1')
console.log('Query result:', result)
}

main()
.then(async () => {
await pool.end()
console.log('Connection closed')
})
.catch(async (error) => {
console.error('Error:', error)
await pool.end()
process.exit(1)
})

运行脚本:

¥Run the script:

npx tsx src/script.ts

你应该收到类似如下的输出:

¥You should receive output similar to:

Query result: Result {
command: 'SELECT',
rowCount: 1,
oid: null,
rows: [ { '?column?': 1 } ],
fields: [
Field {
name: '?column?',
tableID: 0,
columnID: 0,
dataTypeID: 23,
dataTypeSize: 4,
dataTypeModifier: -1,
format: 'text'
}
],
_parsers: [ [Function: parseInteger] ],
_types: { getTypeParser: [Function: getTypeParser] },
RowCtor: null,
rowAsArray: false,
_prebuiltEmptyResultObject: { '?column?': null }
}
Connection closed

下一步

¥Next steps

你已成功将 Drizzle ORM 连接到 Prisma Postgres!对于模式、迁移和查询等更高级的功能,请参阅 Drizzle ORM 文档

¥You've successfully connected Drizzle ORM to Prisma Postgres! For more advanced features like schemas, migrations, and queries, see the Drizzle ORM documentation.