0

我还是 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 略有不同。我在这里寻找简短而正确的解决方案。

4

1 回答 1

0

要获得正确的连接,请将以下代码添加到池所在的模块中:

var getConnection = function(callback) {
    pool.getConnection(function(err, connection) {
        callback(err, connection);
    });
};

module.exports = getConnection;

完成使用后不要忘记添加 end 连接:

connection.release();
于 2021-03-27T14:50:27.973 回答