deno.com
本页内容

连接到数据库

应用程序通常会从数据库存储和检索数据。Deno 支持连接到多种数据库管理系统。

Deno 社区发布了许多第三方模块,方便连接到 MySQL、Postgres 和 MongoDB 等流行数据库。

它们托管在 Deno 的第三方模块网站 deno.land/x

MySQL 跳转到标题

deno_mysql 是 Deno 的 MySQL 和 MariaDB 数据库驱动。

使用 deno_mysql 连接到 MySQL 跳转到标题

首先导入 `mysql` 模块并创建一个新的客户端实例。然后传入一个包含连接详细信息的对象以连接到数据库

main.js
import { Client } from "https://deno.land/x/mysql/mod.ts";

const client = await new Client().connect({
  hostname: "127.0.0.1",
  username: "root",
  db: "dbname",
  password: "password",
});

连接成功后,您可以执行查询、插入数据和检索信息。

Postgres 跳转到标题

deno-postgres 是一个轻量级的 Deno PostgreSQL 驱动,专注于开发者体验。

使用 deno-postgres 连接到 Postgres 跳转到标题

首先,从 `deno-postgres` 模块导入 `Client` 类并创建一个新的客户端实例。然后传入一个包含连接详细信息的对象以连接到数据库

import { Client } from "https://deno.land/x/postgres/mod.ts";

const client = new Client({
  user: "user",
  database: "dbname",
  hostname: "127.0.0.1",
  port: 5432,
  password: "password",
});
await client.connect();

使用 postgresjs 连接到 Postgres 跳转到标题

postgresjs 是一个功能齐全的 Node.js 和 Deno Postgres 客户端。

导入 `postgres` 模块并创建一个新的客户端实例。然后传入连接字符串作为参数以连接到数据库

import postgres from "https://deno.land/x/postgresjs/mod.js";

const sql = postgres("postgres://username:password@host:port/database");

MongoDB 跳转到标题

我们建议使用 npm specifier 来使用官方的 npm 上的 MongoDB 驱动。您可以在官方文档中了解更多关于如何使用该驱动的信息。在 Deno 环境中使用此模块的唯一区别在于您将使用 `npm:` specifier 导入模块的方式。

导入 MongoDB 驱动,设置连接配置,然后连接到 MongoDB 实例。之后,您可以在关闭连接之前执行诸如将文档插入集合等操作。

main.js
import { MongoClient } from "npm:mongodb@6";

const url = "mongodb://localhost:27017";
const client = new MongoClient(url);
const dbName = "myProject";

await client.connect();
console.log("Connected successfully to server");

// Get a reference to a collection
const db = client.db(dbName);
const collection = db.collection("documents");

// Execute an insert operation
const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }]);
console.log("Inserted documents =>", insertResult);

client.close();

SQLite 跳转到标题

在 Deno 中连接到 SQLite 有多种解决方案

使用 node:sqlite 模块连接到 SQLite 跳转到标题

node:sqlite 模块已在 Deno v2.2 中添加。

import { DatabaseSync } from "node:sqlite";
const database = new DatabaseSync("test.db");

const result = database.prepare("select sqlite_version()").get();
console.log(result);

db.close();

使用 FFI 模块连接到 SQLite 跳转到标题

@db/sqlite 使用 Deno FFI 为 SQLite3 C API 提供 JavaScript 绑定。

import { Database } from "jsr:@db/sqlite@0.12";

const db = new Database("test.db");

const [version] = db.prepare("select sqlite_version()").value<[string]>()!;
console.log(version);

db.close();

使用 Wasm 优化模块连接到 SQLite 跳转到标题

sqlite 是一个用于 JavaScript 和 TypeScript 的 SQLite 模块。该封装是专为 Deno 制作的,并使用编译为 WebAssembly (Wasm) 的 SQLite3 版本。

import { DB } from "https://deno.land/x/sqlite/mod.ts";

const db = new DB("test.db");

db.close();

Firebase 跳转到标题

要在 Deno 中连接到 Firebase,请使用 ESM CDN 导入 firestore npm 模块。要了解更多关于在 Deno 中使用 CDN 导入 npm 模块的信息,请参阅 使用 CDN 的 npm 包

使用 firestore npm 模块连接到 Firebase 跳转到标题

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js";

import {
  addDoc,
  collection,
  connectFirestoreEmulator,
  deleteDoc,
  doc,
  Firestore,
  getDoc,
  getDocs,
  getFirestore,
  query,
  QuerySnapshot,
  setDoc,
  where,
} from "https://www.gstatic.com/firebasejs/9.8.1/firebase-firestore.js";

import { getAuth } from "https://www.gstatic.com/firebasejs/9.8.1/firebase-auth.js";

const app = initializeApp({
  apiKey: Deno.env.get("FIREBASE_API_KEY"),
  authDomain: Deno.env.get("FIREBASE_AUTH_DOMAIN"),
  projectId: Deno.env.get("FIREBASE_PROJECT_ID"),
  storageBucket: Deno.env.get("FIREBASE_STORAGE_BUCKET"),
  messagingSenderId: Deno.env.get("FIREBASE_MESSING_SENDER_ID"),
  appId: Deno.env.get("FIREBASE_APP_ID"),
  measurementId: Deno.env.get("FIREBASE_MEASUREMENT_ID"),
});
const db = getFirestore(app);
const auth = getAuth(app);

Supabase 跳转到标题

要在 Deno 中连接到 Supabase,请使用 esm.sh CDN 导入 supabase-js npm 模块。要了解更多关于在 Deno 中使用 CDN 导入 npm 模块的信息,请参阅 使用 CDN 的 npm 包

使用 supabase-js npm 模块连接到 Supabase 跳转到标题

import { createClient } from "https://esm.sh/@supabase/supabase-js";

const options = {
  schema: "public",
  headers: { "x-my-custom-header": "my-app-name" },
  autoRefreshToken: true,
  persistSession: true,
  detectSessionInUrl: true,
};

const supabase = createClient(
  "https://xyzcompany.supabase.co",
  "public-anon-key",
  options,
);

ORM 跳转到标题

对象关系映射 (ORM) 将数据模型定义为可以持久化到数据库的类。您可以通过这些类的实例在数据库中读写数据。

Deno 支持多种 ORM,包括 Prisma 和 DenoDB。

DenoDB 跳转到标题

DenoDB 是一个 Deno 特有的 ORM。

连接到 DenoDB 跳转到标题

import {
  Database,
  DataTypes,
  Model,
  PostgresConnector,
} from "https://deno.land/x/denodb/mod.ts";

const connection = new PostgresConnector({
  host: "...",
  username: "user",
  password: "password",
  database: "airlines",
});

const db = new Database(connection);

GraphQL 跳转到标题

GraphQL 是一种 API 查询语言,常用于将不同的数据源组合成以客户端为中心的 API。要设置 GraphQL API,您应该首先设置一个 GraphQL 服务器。该服务器将您的数据作为 GraphQL API 公开,供您的客户端应用程序查询数据。

服务器 跳转到标题

您可以使用 gql(一个用于 Deno 的通用 GraphQL HTTP 中间件)在 Deno 中运行 GraphQL API 服务器。

使用 gql 运行 GraphQL API 服务器 跳转到标题

import { GraphQLHTTP } from "https://deno.land/x/gql/mod.ts";
import { makeExecutableSchema } from "https://deno.land/x/graphql_tools@0.0.2/mod.ts";
import { gql } from "https://deno.land/x/graphql_tag@0.0.1/mod.ts";

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => `Hello World!`,
  },
};

const schema = makeExecutableSchema({ resolvers, typeDefs });

Deno.serve({ port: 3000 }, async () => {
  const { pathname } = new URL(req.url);

  return pathname === "/graphql"
    ? await GraphQLHTTP<Request>({
      schema,
      graphiql: true,
    })(req)
    : new Response("Not Found", { status: 404 });
});

客户端 跳转到标题

要在 Deno 中进行 GraphQL 客户端调用,请使用 esm CDN 导入 graphql npm 模块。要了解更多关于在 Deno 中通过 CDN 使用 npm 模块的信息,请在此处阅读。

使用 graphql npm 模块进行 GraphQL 客户端调用 跳转到标题

import { buildSchema, graphql } from "https://esm.sh/graphql";

const schema = buildSchema(`
type Query {
  hello: String
}
`);

const rootValue = {
  hello: () => {
    return "Hello world!";
  },
};

const response = await graphql({
  schema,
  source: "{ hello }",
  rootValue,
});

console.log(response);

🦕 现在您可以将您的 Deno 项目连接到数据库,从而能够处理持久化数据、执行 CRUD 操作并开始构建更复杂的应用程序。

您找到所需内容了吗?

隐私政策