Skip to content

Node.js / TypeScript: mysql2 (MySQL)

Connects, creates a todo table if it does not exist, inserts a row and counts open rows. The code is the same against the original database and against MachSQL; only the address changes.

DATABASE_URL=mysql://app:${DB_PASSWORD}@old-mysql:3306/app
DATABASE_URL=mysql://app:${DB_PASSWORD}@machsql-host:3306/app

Nothing else changes: not the code, not the driver, not its version, not the SQL.

  • Node.js 26 LTS
  • mysql2 3.24.6
  • TypeScript 7.0.2, tsx 4.23.15
Terminal window
npm install
export DATABASE_URL=mysql://app:${DB_PASSWORD}@machsql-host:3306/app
npm start

Expected output: inserted todo <id>, <n> open.

The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.

index.ts
// mysql2 (promise API) from TypeScript.
import mysql, { type ResultSetHeader, type RowDataPacket } from "mysql2/promise";
const conn = await mysql.createConnection(process.env.DATABASE_URL ?? "");
try {
await conn.query("CREATE TABLE IF NOT EXISTS todo (id BIGINT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200) NOT NULL, done BOOLEAN NOT NULL DEFAULT FALSE)");
const [inserted] = await conn.execute<ResultSetHeader>("INSERT INTO todo (title) VALUES (?)", ["write the examples"]);
const [rows] = await conn.query<RowDataPacket[]>("SELECT count(*) AS n FROM todo WHERE NOT done");
console.log(`inserted todo ${inserted.insertId}, ${rows[0].n} open`);
} finally {
await conn.end();
}
package.json
{
"name": "machsql-example-node-mysql2",
"private": true,
"type": "module",
"scripts": { "start": "tsx index.ts" },
"dependencies": { "mysql2": "3.24.6" },
"devDependencies": {
"@types/node": "26.6.6",
"tsx": "4.23.15",
"typescript": "7.0.2"
}
}