mysql2 ↗ 是适用于 Node.js 的现代 MySQL 驱动,性能更好且内置 Promise 支持。本示例演示如何将其与 Cloudflare Workers 和 Hyperdrive 配合使用。
安装 mysql2 ↗ 驱动:
npm i mysql2@>3.13.0yarn add mysql2@>3.13.0pnpm add mysql2@>3.13.0bun add mysql2@>3.13.0在 wrangler.jsonc 中添加所需的 Node.js 兼容性标志和 Hyperdrive 绑定:
在 wrangler.jsonc 中添加 Node.js 兼容性标志和 Hyperdrive 绑定(binding):
{
// required for database drivers to function
"compatibility_flags": [
"nodejs_compat"
],
// Set this to today's date
"compatibility_date": "2026-08-17",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"创建新的 connection 实例并传入 Hyperdrive 参数:
// mysql2 v3.13.0 or later is required
import { createConnection } from "mysql2/promise";
export default {
async fetch(request, env, ctx): Promise<Response> {
// Create a new connection on each request. Hyperdrive maintains the underlying
// database connection pool, so creating a new connection is fast.
const connection = await createConnection({
host: env.HYPERDRIVE.host,
user: env.HYPERDRIVE.user,
password: env.HYPERDRIVE.password,
database: env.HYPERDRIVE.database,
port: env.HYPERDRIVE.port,
// Required to enable mysql2 compatibility for Workers
disableEval: true,
});
try {
// Sample query
const [results, fields] = await connection.query("SHOW tables;");
// Return result rows as JSON
return Response.json({ results, fields });
} catch (e) {
console.error(e);
return Response.json(
{ error: e instanceof Error ? e.message : e },
{ status: 500 },
);
}
},
} satisfies ExportedHandler<Env>;