// 添加到文件开头 import sqlite3 from 'sqlite3'; import { promisify } from 'util'; sqlite3.verbose(); // 数据库连接池简单实现 const dbConnections = new Map(); // 打开数据库并添加到连接池 async function openDatabase(dbPath) { console.log(`打开数据库连接: ${dbPath}`); // 检查是否已有连接 if (dbConnections.has(dbPath)) { console.log(`使用现有数据库连接: ${dbPath}`); return dbConnections.get(dbPath); } return new Promise((resolve, reject) => { const db = new sqlite3.Database(dbPath, (err) => { if (err) { console.error(`打开数据库失败: ${err.message}`); reject(err); return; } console.log(`成功打开数据库: ${dbPath}`); // promisify数据库方法 db.getAsync = promisify(db.get).bind(db); db.allAsync = promisify(db.all).bind(db); // 自定义实现runAsync以获取lastID db.runAsync = function(sql, params) { return new Promise((resolve, reject) => { this.run(sql, params, function(err) { if (err) { reject(err); } else { resolve({ lastID: this.lastID, changes: this.changes }); } }); }); }; db.execAsync = promisify(db.exec).bind(db); // 添加到连接池 dbConnections.set(dbPath, db); resolve(db); }); }); } // 添加重试机制的执行函数 async function executeWithRetry(db, operation, maxRetries = 3) { let retries = 0; while (retries < maxRetries) { try { return await operation(); } catch (error) { if (error.code === 'SQLITE_BUSY' && retries < maxRetries - 1) { retries++; console.log(`数据库忙,正在重试 (${retries}/${maxRetries})...`); await new Promise(resolve => setTimeout(resolve, 500 * retries)); // 指数退避 } else { throw error; } } } } // 修改batchInsert函数使用重试机制 async function batchInsert(db, table, data) { if (!data || data.length === 0) { return; } const columns = Object.keys(data[0]).join(', '); const placeholders = data.map(() => { return '(' + Object.keys(data[0]).map(() => '?').join(', ') + ')'; }).join(', '); const values = []; data.forEach(item => { Object.values(item).forEach(value => { values.push(value); }); }); const sql = `INSERT INTO ${table} (${columns}) VALUES ${placeholders}`; return executeWithRetry(db, async () => { await db.runAsync(sql, values); console.log(`成功插入 ${data.length} 条记录到 ${table} 表`); }); } // 导出修改后的函数 export { openDatabase, batchInsert, executeWithRetry };