deno.com
本页内容

连接到数据库

应用程序通常需要存储和检索数据库中的数据。Deno 支持连接到许多数据库管理系统。

Deno 社区发布了许多第三方模块,可以轻松连接到流行的数据库,如 MySQL、Postgres 和 MongoDB。

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

MySQL Jump to heading

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

使用 deno_mysql 连接到 MySQL Jump to heading

首先导入 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 Jump to heading

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

使用 deno-postgres 连接到 Postgres Jump to heading

首先,从 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 Jump to heading

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

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

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

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

MongoDB Jump to heading

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

导入 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 Jump to heading

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

使用 node:sqlite 模块连接到 SQLite Jump to heading

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 Jump to heading

@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 Jump to heading

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 Jump to heading

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

使用 firestore npm 模块连接到 Firebase Jump to heading

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 Jump to heading

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

使用 supabase-js npm 模块连接到 Supabase Jump to heading

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,
);

ORMs Jump to heading

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

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

DenoDB Jump to heading

DenoDB 是一个 Deno 专用的 ORM。

连接到 DenoDB Jump to heading

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 Jump to heading

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

服务器 Jump to heading

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

使用 gql 运行 GraphQL API 服务器 Jump to heading

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 });
});

客户端 Jump to heading

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

使用 graphql npm 模块进行 GraphQL 客户端调用 Jump to heading

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 操作并开始构建更复杂的应用程序。

您找到所需的信息了吗?

隐私政策