跳转到内容
搜索文档

mysql 示例

最后更新 查看 MarkdownAgent 设置

mysql 是 Node.js 的经典 MySQL 驱动。本示例演示如何将其与 Cloudflare Workers 和 Hyperdrive 配合使用。

安装 mysql 驱动:

npm i mysql

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>"

创建新连接并传入 Hyperdrive 参数:

import { createConnection } from "mysql";

export default {
	async fetch(request, env, ctx): Promise<Response> {
		const result = await new Promise<any>((resolve) => {
			// Create a connection using the mysql driver with the Hyperdrive credentials (only accessible from your Worker).
			const connection = createConnection({
				host: env.HYPERDRIVE.host,
				user: env.HYPERDRIVE.user,
				password: env.HYPERDRIVE.password,
				database: env.HYPERDRIVE.database,
				port: env.HYPERDRIVE.port,
			});

			connection.connect((error: { message: string }) => {
				if (error) {
					throw new Error(error.message);
				}

				// Sample query
				connection.query("SHOW tables;", [], (error, rows, fields) => {
					resolve({ fields, rows });
				});
			});
		});

		// Return result  as JSON
		return new Response(JSON.stringify(result), {
			headers: {
				"Content-Type": "application/json",
			},
		});
	},
} satisfies ExportedHandler<Env>;

这篇文档对您有帮助吗?