问题描述
我对 nodejs 还是个新手,无法理解一些东西。 我有带代码的 db.js 文件:
function connection() {
try {
const MysqL = require('MysqL2');
const pool = MysqL.createPool({
host: 'localhost',user: 'user',password: 'password',database: 'database',waitForConnections: true,connectionLimit: 15,queueLimit: 0,multipleStatements: true
});
const promisePool = pool.promise();
return promisePool;
} catch (error) {
return console.log(`Could not connect - ${error}`);
}
}
const pool = connection();
module.exports = {
connection: async () => pool.getConnection(),execute: (...params) => pool.execute(...params)
};
当我尝试插入这样的行时:
! async function() {
var sql = {
title: 'title',url: 'url',content: 'content'
};
const [query] = await db.execute("INSERT INTO content SET ?",[sql]);
}();
它因 sql 语法错误而失败。为什么它失败了,它运行良好,与 db.js 略有不同。 我在这里寻找简短而正确的解决方案。
解决方法
要获得正确的连接,请将以下代码添加到池所在的模块中:
var getConnection = function(callback) {
pool.getConnection(function(err,connection) {
callback(err,connection);
});
};
module.exports = getConnection;
使用完毕后不要忘记添加结束连接:
connection.release();