Mysql8
- 版本
"mysql2": "^3.14.1" - 安装
npm i mysql2@3.14.1
最小示例
javascript
// 数据库操作模块
const mysql = require('mysql2/promise');
class DbAdapter {
constructor(config) {
this.pool = mysql.createPool({
host: config.host,
user: config.user,
password: config.password,
database: config.database,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
this._checkDB()
}
async _checkDB() {
const sql = `select 1`;
await this.pool.execute(sql);
console.log(`数据库连接成功`);
}
/** 插 */
async insertBook(book) {
const sql = `
INSERT INTO books (
base_folder_id,
title,
author,
preview,
notes
) VALUES (?, ?, ?, ?, ?)
`;
const values = [
book.baseFolderId || 0,
book.title,
book.author || null,
book.preview || null,
book.notes || null,
];
await this.pool.execute(sql, values);
}
async getBaseFolders() {
const [rows] = await this.pool.execute(
'SELECT * FROM base_folders WHERE status = ?',
[1]
);
return rows || [];
}
/** 查 */
async getBookByFileNames(fileName) {
const [rows] = await this.pool.execute(
'SELECT * FROM base_books WHERE file_name = ?',
[fileName]
);
return rows || null;
}
/** 更 */
async updateFileVersion(relativePath) {
const [result] = await this.pool.execute(
'UPDATE books SET version = version + 1, mtime = NOW() WHERE relativePath = ?',
[relativePath]
);
return result.affectedRows > 0;
}
async close() {
await this.pool.end();
}
}
module.exports = DbAdapter;