Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

mysql

最終更新 Markdown で表示Agent セットアップ

mysql パッケージは、Node.js 向けの MySQL ドライバーです。 この例では、Cloudflare Workers と Hyperdrive での使い方を示します。

mysql ドライバーをインストールします。

npm i mysql

必要な Node.js 互換性フラグと Hyperdrive バインディングを wrangler.jsonc ファイルに追加します。

{
	// required for database drivers to function
	"compatibility_flags": [
		"nodejs_compat"
	],
	// Set this to today's date
	"compatibility_date": "2026-09-20",
	"hyperdrive": [
		{
			"binding": "HYPERDRIVE",
			"id": "<your-hyperdrive-id-here>"
		}
	]
}
compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-09-20"

[[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>;

役に立ちましたか?