SQLite 快速入门
在本快速入门指南中,你将学习如何使用纯 TypeScript 项目和本地 SQLite 数据库文件从头开始使用 Prisma ORM。它涵盖数据建模、迁移和数据库查询。
¥In this Quickstart guide, you'll learn how to get started with Prisma ORM from scratch using a plain TypeScript project and a local SQLite database file. It covers data modeling, migrations and querying a database.
如果你想将 Prisma ORM 与你自己的 PostgreSQL、MySQL、MongoDB 或任何其他支持的数据库一起使用,请转至此处:
¥If you want to use Prisma ORM with your own PostgreSQL, MySQL, MongoDB or any other supported database, go here instead:
先决条件
¥Prerequisites
你需要在你的机器上安装 Node.js(请参阅 系统要求 了解官方支持的版本)。
¥You need Node.js installed on your machine (see system requirements for officially supported versions).
1. 创建 TypeScript 项目并设置 Prisma ORM
¥ Create TypeScript project and set up Prisma ORM
第一步,创建一个项目目录并导航到其中:
¥As a first step, create a project directory and navigate into it:
mkdir hello-prisma
cd hello-prisma
接下来,使用 npm 初始化 TypeScript 项目:
¥Next, initialize a TypeScript project using npm:
npm init -y
npm install typescript tsx @types/node --save-dev
这会创建一个 package.json
,并为你的 TypeScript 应用进行初始设置。
¥This creates a package.json
with an initial setup for your TypeScript app.
请参阅 安装说明 了解如何使用不同的包管理器安装 Prisma。
¥See installation instructions to learn how to install Prisma using a different package manager.
现在,初始化 TypeScript:
¥Now, initialize TypeScript:
npx tsc --init
然后,在项目中安装 Prisma CLI 作为开发依赖:
¥Then, install the Prisma CLI as a development dependency in the project:
npm install prisma --save-dev
最后,使用 Prisma CLI 的 init
命令设置 Prisma ORM:
¥Finally, set up Prisma ORM with the init
command of the Prisma CLI:
npx prisma init --datasource-provider sqlite --output ../generated/prisma
这将创建一个带有 schema.prisma
文件的新 prisma
目录,并将 SQLite 配置为你的数据库。你现在已准备好对数据进行建模并使用一些表创建数据库。
¥This creates a new prisma
directory with a schema.prisma
file and configures SQLite as your database. You're now ready to model your data and create your database with some tables.
2. 在 Prisma 架构中对数据进行建模
¥ Model your data in the Prisma schema
Prisma 模式提供了一种直观的数据建模方法。将以下模型添加到你的 schema.prisma
文件中:
¥The Prisma schema provides an intuitive way to model data. Add the following models to your schema.prisma
file:
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}
Prisma 模式中的模型有两个主要用途:
¥Models in the Prisma schema have two main purposes:
-
代表底层数据库中的表
¥Represent the tables in the underlying database
-
作为生成的 Prisma 客户端 API 的基础
¥Serve as foundation for the generated Prisma Client API
在下一部分中,你将使用 Prisma Migrate 将这些模型映射到数据库表。
¥In the next section, you will map these models to database tables using Prisma Migrate.
3. 使用 Prisma Migrate 运行迁移以创建数据库表
¥ Run a migration to create your database tables with Prisma Migrate
此时,你已经有了 Prisma 架构,但还没有数据库。在终端中运行以下命令来创建 SQLite 数据库以及模型代表的 User
和 Post
表:
¥At this point, you have a Prisma schema but no database yet. Run the following command in your terminal to create the SQLite database and the User
and Post
tables represented by your models:
npx prisma migrate dev --name init
该命令做了三件事:
¥This command did three things:
-
它在
prisma/migrations
目录中为此迁移创建了一个新的 SQL 迁移文件。¥It created a new SQL migration file for this migration in the
prisma/migrations
directory. -
它针对数据库执行 SQL 迁移文件。
¥It executed the SQL migration file against the database.
-
它在后台运行
prisma generate
(安装了@prisma/client
软件包并根据你的模型生成了定制的 Prisma 客户端 API)。¥It ran
prisma generate
under the hood (which installed the@prisma/client
package and generated a tailored Prisma Client API based on your models).
由于 SQLite 数据库文件之前不存在,因此该命令还在 prisma
目录中创建了它,名称为 dev.db
,通过 .env
文件中的环境变量定义。
¥Because the SQLite database file didn't exist before, the command also created it inside the prisma
directory with the name dev.db
as defined via the environment variable in the .env
file.
恭喜,你现在已准备好数据库和表。让我们来学习如何发送一些查询来读取和写入数据!
¥Congratulations, you now have your database and tables ready. Let's go and learn how you can send some queries to read and write data!
4. 探索如何使用 Prisma 客户端将查询发送到数据库
¥ Explore how to send queries to your database with Prisma Client
要开始使用 Prisma Client,你需要安装 @prisma/client
软件包:
¥To get started with Prisma Client, you need to install the @prisma/client
package:
npm install @prisma/client
安装命令会为你调用 prisma generate
,它会读取你的 Prisma 架构并生成适合你的模型的 Prisma 客户端版本。
¥The install command invokes prisma generate
for you which reads your Prisma schema and generates a version of Prisma Client that is tailored to your models.
要将查询发送到数据库,你将需要一个 TypeScript 文件来执行 Prisma 客户端查询。为此创建一个名为 script.ts
的新文件:
¥To send queries to the database, you will need a TypeScript file to execute your Prisma Client queries. Create a new file called script.ts
for this purpose:
touch script.ts
然后,将以下样板粘贴到其中:
¥Then, paste the following boilerplate into it:
import { PrismaClient } from './generated/prisma'
const prisma = new PrismaClient()
async function main() {
// ... you will write your Prisma Client queries here
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
此代码包含在脚本末尾调用的 main
函数。它还实例化 PrismaClient
,它代表数据库的查询接口。
¥This code contains a main
function that's invoked at the end of the script. It also instantiates PrismaClient
which represents the query interface to your database.
4.1.创建新的 User
记录
¥4.1. Create a new User
record
让我们从一个小查询开始,在数据库中创建一个新的 User
记录并将结果对象记录到控制台。将以下代码添加到你的 script.ts
文件中:
¥Let's start with a small query to create a new User
record in the database and log the resulting object to the console. Add the following code to your script.ts
file:
import { PrismaClient } from './generated/prisma'
const prisma = new PrismaClient()
async function main() {
const user = await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
},
})
console.log(user)
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
你无需复制代码,只需在编辑器中输入代码即可体验 Prisma Client 提供的自动补齐功能。你还可以通过按键盘上的 CTRL+SPACE 键主动调用自动补齐功能。
¥Instead of copying the code, you can type it out in your editor to experience the autocompletion Prisma Client provides. You can also actively invoke the autocompletion by pressing the CTRL+SPACE keys on your keyboard.
接下来,使用以下命令执行脚本:
¥Next, execute the script with the following command:
npx tsx script.ts
{ id: 1, email: 'alice@prisma.io', name: 'Alice' }
干得好,你刚刚使用 Prisma 客户端创建了你的第一个数据库记录!🎉
¥Great job, you just created your first database record with Prisma Client! 🎉
在下一节中,你将学习如何从数据库读取数据。
¥In the next section, you'll learn how to read data from the database.
4.2.检索所有 User
条记录
¥4.2. Retrieve all User
records
Prisma 客户端提供各种查询来从数据库读取数据。在本部分中,你将使用 findMany
查询返回数据库中给定模型的所有记录。
¥Prisma Client offers various queries to read data from your database. In this section, you'll use the findMany
query that returns all the records in the database for a given model.
删除之前的 Prisma Client 查询并添加新的 findMany
查询:
¥Delete the previous Prisma Client query and add the new findMany
query instead:
import { PrismaClient } from './generated/prisma'
const prisma = new PrismaClient()
async function main() {
const users = await prisma.user.findMany()
console.log(users)
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
再次执行脚本:
¥Execute the script again:
npx tsx script.ts
[{ id: 1, email: 'alice@prisma.io', name: 'Alice' }]
请注意,单个 User
对象现在如何在控制台中用方括号括起来。这是因为 findMany
返回了一个数组,里面有一个对象。
¥Notice how the single User
object is now enclosed with square brackets in the console. That's because the findMany
returned an array with a single object inside.
4.3.使用 Prisma 客户端探索关系查询
¥4.3. Explore relation queries with Prisma Client
Prisma 客户端的主要功能之一是易于使用 relations。在本部分中,你将了解如何在嵌套写入查询中创建 User
和 Post
记录。然后,你将看到如何使用 include
选项从数据库中检索关系。
¥One of the main features of Prisma Client is the ease of working with relations. In this section, you'll learn how to create a User
and a Post
record in a nested write query. Afterwards, you'll see how you can retrieve the relation from the database using the include
option.
首先,调整脚本以包含嵌套查询:
¥First, adjust your script to include the nested query:
import { PrismaClient } from './generated/prisma'
const prisma = new PrismaClient()
async function main() {
const user = await prisma.user.create({
data: {
name: 'Bob',
email: 'bob@prisma.io',
posts: {
create: [
{
title: 'Hello World',
published: true
},
{
title: 'My second post',
content: 'This is still a draft'
}
],
},
},
})
console.log(user)
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
通过再次执行脚本来运行查询:
¥Run the query by executing the script again:
npx tsx script.ts
{ id: 2, email: 'bob@prisma.io', name: 'Bob' }
默认情况下,Prisma 客户端仅返回查询结果对象中的标量字段。这就是为什么,即使你还为新的 User
记录创建了新的 Post
记录,控制台也只打印了一个具有三个标量字段的对象:id
、email
和 name
。
¥By default, Prisma Client only returns scalar fields in the result objects of a query. That's why, even though you also created a new Post
record for the new User
record, the console only printed an object with three scalar fields: id
, email
and name
.
为了还检索属于 User
的 Post
记录,你可以通过 posts
关系字段使用 include
选项:
¥In order to also retrieve the Post
records that belong to a User
, you can use the include
option via the posts
relation field:
import { PrismaClient } from './generated/prisma'
const prisma = new PrismaClient()
async function main() {
const usersWithPosts = await prisma.user.findMany({
include: {
posts: true,
},
})
console.dir(usersWithPosts, { depth: null })
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
再次运行脚本以查看嵌套读取查询的结果:
¥Run the script again to see the results of the nested read query:
npx tsx script.ts
[
{ id: 1, email: 'alice@prisma.io', name: 'Alice', posts: [] },
{
id: 2,
email: 'bob@prisma.io',
name: 'Bob',
posts: [
{
id: 1,
title: 'Hello World',
content: null,
published: true,
authorId: 2
},
{
id: 2,
title: 'My second post',
content: 'This is still a draft',
published: false,
authorId: 2
}
]
}
]
这次,你将看到两个 User
对象被打印。它们都有一个 posts
字段(对于 "Alice"
为空,对于 "Bob"
填充了两个 Post
对象),代表与它们关联的 Post
记录。
¥This time, you're seeing two User
objects being printed. Both of them have a posts
field (which is empty for "Alice"
and populated with two Post
objects for "Bob"
) that represents the Post
records associated with them.
请注意,usersWithPosts
数组中的对象也是完全类型化的。这意味着你将获得自动补全功能,并且 TypeScript 编译器将防止你意外键入它们。
¥Notice that the objects in the usersWithPosts
array are fully typed as well. This means you will get autocompletion and the TypeScript compiler will prevent you from accidentally typing them.
5. 下一步
¥ Next steps
在本快速入门指南中,你学习了如何在普通 TypeScript 项目中开始使用 Prisma ORM。你可以自行更多地探索 Prisma Client API,例如 通过在 findMany
查询中包含过滤、排序和分页选项或探索更多操作(如 update
和 delete
查询)。
¥In this Quickstart guide, you have learned how to get started with Prisma ORM in a plain TypeScript project. Feel free to explore the Prisma Client API a bit more on your own, e.g. by including filtering, sorting, and pagination options in the findMany
query or exploring more operations like update
and delete
queries.
探索 Prisma Studio 中的数据
¥Explore the data in Prisma Studio
Prisma ORM 附带一个内置 GUI,用于查看和编辑数据库中的数据。你可以使用以下命令打开它:
¥Prisma ORM comes with a built-in GUI to view and edit the data in your database. You can open it using the following command:
npx prisma studio
使用你自己的数据库设置 Prisma ORM
¥Set up Prisma ORM with your own database
如果你想使用自己的 PostgreSQL、MySQL、MongoDB 或任何其他受支持的数据库继续使用 Prisma ORM,请按照设置 Prisma ORM 指南进行操作:
¥If you want to move forward with Prisma ORM using your own PostgreSQL, MySQL, MongoDB or any other supported database, follow the Set Up Prisma ORM guides:
使用 Prisma Optimize 获取查询洞察和分析
¥Get query insights and analytics with Prisma Optimize
Prisma 优化 可帮助你生成洞察并提供建议,帮助你加快数据库查询速度。
¥Prisma Optimize helps you generate insights and provides recommendations that can help you make your database queries faster.
Optimize 旨在帮助各个技能水平的开发者编写高效的数据库查询,减少数据库负载并提高应用的响应速度。
¥Optimize aims to help developers of all skill levels write efficient database queries, reducing database load and making applications more responsive.
探索可立即运行的 Prisma ORM 示例
¥Explore ready-to-run Prisma ORM examples
查看 GitHub 上的 prisma-examples
存储库,了解如何将 Prisma ORM 与你喜欢的库一起使用。该存储库包含 Express、NestJS、GraphQL 的示例以及 Next.js 和 Vue.js 的全栈示例等等。
¥Check out the prisma-examples
repository on GitHub to see how Prisma ORM can be used with your favorite library. The repo contains examples with Express, NestJS, GraphQL as well as fullstack examples with Next.js and Vue.js, and a lot more.
使用 Prisma Accelerate 加速数据库查询
¥Speed up your database queries with Prisma Accelerate
Prisma 加速 是一个连接池和全局数据库缓存,可以大大加快数据库查询速度。查看 速度测试 或尝试使用你最喜欢的框架加速:
¥Prisma Accelerate is a connection pooler and global database cache that can drastically speed up your database queries. Check out the Speed Test or try Accelerate with your favorite framework:
演示 | 描述 |
---|---|
nextjs-starter | 使用 Prisma Accelerate 的缓存和连接池的 Next.js 项目 |
svelte-starter | 使用 Prisma Accelerate 的缓存和连接池的 SvelteKit 项目 |
solidstart-starter | 使用 Prisma Accelerate 的缓存和连接池的 Solidstart 项目 |
remix-starter | 使用 Prisma Accelerate 的缓存和连接池的 Remix 项目 |
nuxt-starter | 使用 Prisma Accelerate 的缓存和连接池的 Nuxt.js 项目 |
astro-starter | 使用 Prisma Accelerate 的缓存和连接池的 Astro 项目 |
使用 Prisma ORM 构建应用
¥Build an app with Prisma ORM
Prisma 博客提供有关 Prisma ORM 的综合教程,请查看我们的最新教程:
¥The Prisma blog features comprehensive tutorials about Prisma ORM, check out our latest ones:
-
使用 Remix 构建全栈应用(5 部分,包括视频)
¥Build a fullstack app with Remix (5 parts, including videos)
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.