try { const { Pool, Client } = require('pg') const XLSX = require('xlsx') const path = require('path') // 连接数据库 const pool = new Pool({ user: 'postgres', host: '10.8.30.32', database: 'video_access', password: '123', port: 5432, }) const fun = async () => { // note: we don't try/catch this because if connecting throws an exception // we don't need to dispose of the client (it will be undefined) const client = await pool.connect() try { await client.query('BEGIN') // 读取数据文件 let workbook = XLSX.readFile(path.join(__dirname, '云录制错误码.xlsx')) let firstSheetName = workbook.SheetNames[0]; let worksheet = workbook.Sheets[firstSheetName]; let res = XLSX.utils.sheet_to_json(worksheet); // console.log(res); for (let d of res) { let statusRes = await client.query(`SELECT * FROM camera_status WHERE status=$1`, [d['错误码']]); let statusRows = statusRes.rows if (statusRows.length) { } else { console.log(`增加${d['错误码']}`); const statusInQuery = `INSERT INTO "camera_status" (platform, status, describe, paraphrase) VALUES($1, $2, $3, $4) RETURNING id;` const statusRows = (await client.query(statusInQuery, ['yingshi', d['错误码'], d['错误描述'], d['释义']])).rows // console.log(statusRows); if (d['解决方案']) { let resolveArr = d['解决方案'].split(';'); // await client.query(`DELETE FROM "camera_status_solution" WHERE status_id=$1`, [statusRows[0].id]); for (let r of resolveArr) { await client.query( `INSERT INTO "camera_status_resolve" (status_id, resolve) VALUES($1, $2) RETURNING id;`, [statusRows[0].id, r] ) } } } } // await client.query('ROLLBACK') await client.query('COMMIT') console.log('执行完毕~') } catch (e) { await client.query('ROLLBACK') console.log('执行错误~') throw e } finally { client.release(); } } fun() } catch (error) { console.error(error) }