← Hyperdrive (Postgres & MySQL) / hyperdrive / examples / connect-to-mysql / mysql-drivers-and-libraries
mysql
mysql ↗ представляет собой драйвер MySQL для Node.js. В этом примере показано, как использовать его вместе с 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-08-28",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-28"
[[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>;