使用 TypeScript 和 Prisma ORM 查询现有的 SQL Server 数据库
使用 Prisma 客户端编写你的第一个查询
¥Write your first query with Prisma Client
现在你已经生成了 Prisma 客户端,你可以开始编写查询以在数据库中读取和写入数据。
¥Now that you have generated Prisma Client, you can start writing queries to read and write data in your database.
如果你正在构建 REST API,则可以在路由处理程序中使用 Prisma Client 根据传入的 HTTP 请求在数据库中读取和写入数据。如果你正在构建 GraphQL API,则可以在解析器中使用 Prisma Client 根据传入查询和突变在数据库中读取和写入数据。
¥If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations.
然而,就本指南而言,你只需创建一个简单的 Node.js 脚本来了解如何使用 Prisma Client 将查询发送到数据库。一旦你了解了 API 的工作原理,你就可以开始将其集成到实际的应用代码中(例如 REST 路由处理程序或 GraphQL 解析器)。
¥For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers).
创建一个名为 index.ts
的新文件并添加以下代码:
¥Create a new file named index.ts
and add the following code to it:
import { PrismaClient } from '@prisma/client'
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)
})
以下是代码片段不同部分的快速概述:
¥Here's a quick overview of the different parts of the code snippet:
-
从
@prisma/client
节点模块导入PrismaClient
构造函数¥Import the
PrismaClient
constructor from the@prisma/client
node module -
实例化
PrismaClient
¥Instantiate
PrismaClient
-
定义一个名为
main
的async
函数来向数据库发送查询¥Define an
async
function namedmain
to send queries to the database -
调用
main
函数¥Call the
main
function -
脚本终止时关闭数据库连接
¥Close the database connections when the script terminates
根据你的模型的外观,Prisma 客户端 API 也会有所不同。例如,如果你有 User
模型,则 PrismaClient
实例会公开一个名为 user
的属性,你可以在该属性上调用 CRUD 方法,例如 findMany
、create
或 update
。该属性以型号命名,但第一个字母小写(因此对于 Post
型号,它称为 post
,对于 Profile
,它称为 profile
)。
¥Depending on what your models look like, the Prisma Client API will look different as well. For example, if you have a User
model, your PrismaClient
instance exposes a property called user
on which you can call CRUD methods like findMany
, create
or update
. The property is named after the model, but the first letter is lowercased (so for the Post
model it's called post
, for Profile
it's called profile
).
以下示例均基于 Prisma 架构中的模型。
¥The following examples are all based on the models in the Prisma schema.
在 main
函数中,添加以下查询以从数据库读取所有 User
记录并打印结果:
¥Inside the main
function, add the following query to read all User
records from the database and print the result:
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}
现在使用当前的 TypeScript 设置运行代码。如果你使用的是 tsx
,你可以像这样运行它:
¥Now run the code with your current TypeScript setup. If you're using tsx
, you can run it like this:
npx tsx index.ts
如果你使用数据库自省步骤中的架构创建了数据库,则查询应打印一个空数组,因为数据库中尚无 User
记录。
¥If you created a database using the schema from the database introspection step, the query should print an empty array because there are no User
records in the database yet.
[]
如果你内省了包含记录的现有数据库,则查询应返回 JavaScript 对象数组。
¥If you introspected an existing database with records, the query should return an array of JavaScript objects.
将数据写入数据库
¥Write data into the database
你在上一节中使用的 findMany
查询仅从数据库中读取数据。在本节中,你将学习如何编写查询以将新记录写入 Post
和 User
表中。
¥The findMany
query you used in the previous section only reads data from the database. In this section, you'll learn how to write a query to write new records into the Post
and User
tables.
调整 main
函数以向数据库发送 create
查询:
¥Adjust the main
function to send a create
query to the database:
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
})
const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true,
},
})
console.dir(allUsers, { depth: null })
}
此代码使用 嵌套写入 查询创建新的 User
记录以及新的 Post
和 Profile
记录。User
记录分别通过 Post.author
↔ User.posts
和 Profile.user
↔ User.profile
关系字段 连接到另外两个记录。
¥This code creates a new User
record together with new Post
and Profile
records using a nested write query. The User
record is connected to the two other ones via the Post.author
↔ User.posts
and Profile.user
↔ User.profile
relation fields respectively.
请注意,你将 include
选项传递给 findMany
,这告诉 Prisma 客户端在返回的 User
对象上包含 posts
和 profile
关系。
¥Notice that you're passing the include
option to findMany
which tells Prisma Client to include the posts
and profile
relations on the returned User
objects.
使用当前的 TypeScript 设置运行代码。如果你使用的是 tsx
,你可以像这样运行它:
¥Run the code with your current TypeScript setup. If you're using tsx
, you can run it like this:
npx tsx index.ts
在继续下一部分之前,你需要对刚刚使用 update
查询创建的 Post
记录进行 "publish" 操作。调整 main
功能如下:
¥Before moving on to the next section, you'll "publish" the Post
record you just created using an update
query. Adjust the main
function as follows:
async function main() {
const post = await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
console.log(post)
}
使用当前的 TypeScript 设置运行代码。如果你使用的是 tsx
,你可以像这样运行它:
¥Run the code with your current TypeScript setup. If you're using tsx
, you can run it like this:
npx tsx index.ts