0

I'm still new to nodejs and cannot understand something. I have db.js file with code:

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)
};

When i try to insert row like this:

! async function() {
  var sql = {
    title: 'title',
    url: 'url',
    content: 'content'
  };
  const [query] = await db.execute("INSERT INTO content SET ?",[sql]);
}();

It fails with sql syntax error. Why it fails, it worked fine, with slightly different db.js. I'm looking for the short and correct solution here.

yieChug1
  • 85
  • 7

1 Answers1

0

To get a proper connection, add the following code to your module where the pool is in:

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

module.exports = getConnection;

Don't forget to add end the connection when you are done using it:

connection.release();
Ruhul Amin
  • 821
  • 11
  • 14
  • I don't know, maybe i past your code in a wrong place, but it says connection.execute is not a function – yieChug1 Mar 27 '21 at 15:02
  • Did you tried with it ? const [query] = await db.execute("INSERT INTO content SET title = ?, url = ?, content = ?",[sql.title, sql.title, sql.content]); – Ruhul Amin Mar 27 '21 at 15:33
  • Yes i tried and it's long, i have a lot of columns in db. – yieChug1 Mar 27 '21 at 16:38