import { DatabaseSync } from 'node:sqlite';
function buildConnectionConfig(overrides = {}) {
return {
host: 'localhost',
user: 'root',
password: '',
port: 3306,
database: 'test',
charset: 'UTF8_GENERAL_CI',
timezone: 'local',
connectTimeout: 0,
stringifyObjects: false,
typeCast: true,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: false,
multipleStatements: false,
...overrides,
};
}
function main() {
const db = new DatabaseSync(':memory:');
const cases = [];
try {
// Case 1: connection_config_and_select_probe
const cfg = buildConnectionConfig({ database: 'app_demo' });
const probeRow = db.prepare('SELECT 1 + 1 AS solution').get();
const actual1 = {
host: cfg.host,
port: cfg.port,
charset: cfg.charset,
typeCast: cfg.typeCast,
multipleStatements: cfg.multipleStatements,
solution: probeRow.solution,
};
const expected1 = {
host: 'localhost',
port: 3306,
charset: 'UTF8_GENERAL_CI',
typeCast: true,
multipleStatements: false,
solution: 2,
};
cases.push({
name: 'connection_config_and_select_probe',
passed: JSON.stringify(actual1) === JSON.stringify(expected1),
expected: expected1,
actual: actual1,
});
// Case 2: websites_table_seed_and_select
db.exec(`
CREATE TABLE websites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
url TEXT NOT NULL,
alexa INTEGER NOT NULL,
country TEXT NOT NULL
);
`);
const seedStmt = db.prepare(
'INSERT INTO websites (name, url, alexa, country) VALUES (?, ?, ?, ?)',
);
const seeds = [
['Google', 'https://www.google.com/', 1, 'USA'],
['淘宝', 'https://www.taobao.com/', 13, 'CN'],
['蓝色天空', 'https://www.mbsky.example/', 4689, 'CN'],
['微博', 'https://weibo.com/', 20, 'CN'],
['Facebook', 'https://www.facebook.com/', 3, 'USA'],
];
for (const row of seeds) seedStmt.run(...row);
const allRows = db.prepare('SELECT id, name, url, alexa, country FROM websites ORDER BY id').all();
const cnCount = db.prepare('SELECT COUNT(*) AS cnt FROM websites WHERE country = ?').get('CN').cnt;
const actual2 = {
totalRows: allRows.length,
firstSite: allRows[0].name,
cnCount,
ids: allRows.map((r) => r.id),
};
const expected2 = {
totalRows: 5,
firstSite: 'Google',
cnCount: 3,
ids: [1, 2, 3, 4, 5],
};
cases.push({
name: 'websites_table_seed_and_select',
passed: JSON.stringify(actual2) === JSON.stringify(expected2),
expected: expected2,
actual: actual2,
});
// Case 3: parameterized_insert_update_delete_crud
const insRes = db
.prepare('INSERT INTO websites (name, url, alexa, country) VALUES (?, ?, ?, ?)')
.run('开发者工具', 'https://tools.mbsky.example/', 23453, 'CN');
const insertedId = Number(insRes.lastInsertRowid);
const updRes = db
.prepare('UPDATE websites SET name = ?, url = ? WHERE id = ?')
.run('移动工具站', 'https://m.mbsky.example/', insertedId);
const updatedRow = db.prepare('SELECT name, url FROM websites WHERE id = ?').get(insertedId);
const delRes = db.prepare('DELETE FROM websites WHERE id = ?').run(insertedId);
const remainingCount = db.prepare('SELECT COUNT(*) AS cnt FROM websites').get().cnt;
const actual3 = {
insertedId,
insertChanges: insRes.changes,
updateChanges: updRes.changes,
updatedName: updatedRow.name,
updatedUrl: updatedRow.url,
deleteChanges: delRes.changes,
remainingCount,
};
const expected3 = {
insertedId: 6,
insertChanges: 1,
updateChanges: 1,
updatedName: '移动工具站',
updatedUrl: 'https://m.mbsky.example/',
deleteChanges: 1,
remainingCount: 5,
};
cases.push({
name: 'parameterized_insert_update_delete_crud',
passed: JSON.stringify(actual3) === JSON.stringify(expected3),
expected: expected3,
actual: actual3,
});
// Case 4: sql_injection_guard_via_placeholders
const malicious = "' OR '1'='1";
const matched = db.prepare('SELECT id, name FROM websites WHERE name = ?').all(malicious);
const stillCount = db.prepare('SELECT COUNT(*) AS cnt FROM websites').get().cnt;
const actual4 = { matchedCount: matched.length, tableRowCount: stillCount };
const expected4 = { matchedCount: 0, tableRowCount: 5 };
cases.push({
name: 'sql_injection_guard_via_placeholders',
passed: JSON.stringify(actual4) === JSON.stringify(expected4),
expected: expected4,
actual: actual4,
});
} finally {
db.close();
}
console.log(JSON.stringify({ version: process.version, cases }));
}
main();
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、Node.js v24.22.3 本地运行环境。
入口文件:projects/nodejs-mysql-lab/explore-mysql.mjs
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-mysql.mjs,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1060.zip