【问题标题】:Node.js mysql2 connection pool execution issueNode.js mysql2 连接池执行问题
【发布时间】:2021-03-27 14:40:24
【问题描述】:

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

【问题讨论】:

    标签: sql node.js node-mysql2


    【解决方案1】:

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

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

    使用完后别忘了添加 end 连接:

    connection.release();
    

    【讨论】:

    • 我不知道,也许我把你的代码放在了错误的地方,但它说 connection.execute 不是一个函数
    • 你试过了吗? const [query] = await db.execute("INSERT INTO content SET title = ?, url = ?, content = ?",[sql.title, sql.title, sql.content]);
    • 是的,我试过了,它很长,我在 db 中有很多列。
    猜你喜欢
    • 1970-01-01
    • 2011-04-01
    • 2012-09-25
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多