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.
The only change
Section titled “The only change”DATABASE_URL=mysql://app:${DB_PASSWORD}@old-mysql:3306/appDATABASE_URL=mysql://app:${DB_PASSWORD}@machsql-host:3306/appNothing else changes: not the code, not the driver, not its version, not the SQL.
Versions
Section titled “Versions”- Node.js 26 LTS
- mysql2 3.24.6
- TypeScript 7.0.2, tsx 4.23.15
npm installexport DATABASE_URL=mysql://app:${DB_PASSWORD}@machsql-host:3306/appnpm startExpected output: inserted todo <id>, <n> open.
Source
Section titled “Source”The program as it is kept and tested in the Mach Database for PostgreSQL repository; highlighted lines read the connection setting.
// 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();}{ "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" }}