Hi I am trying to execute a node.js function that opens a database connection, executes a query and then closes.
Everything works fine up until the point where I need the connection to close. I am assuming something is wrong with my syntax but I can't figure it out.
Here's the code:
async function databaseConnection() {
const mysql = require('mysql2/promise');
var connection = await mysql.createConnection({
host:'*******'
, user:'*******'
, password:'*******'
, database:'*******'
});
var q = 'SELECT ******* AS sha1 FROM ******* limit 10';
await connection.execute(q, function(err, rows, fields) {
if(err){
console.log("An error ocurred performing the query." + err);
return;
}else{
console.log("Query succesfully executed: ");
rows.forEach( (row) => {
console.log('sha1 from db row: ' + row.sha1);
});
}
});
await connection.end();
}
databaseConnection();
Nik Kyriakides made a good point about mixing async/await with callbacks which solved my problem. I'll paste it here to answer the question:
I don't know about your connection end issues but this line looks wrong: await connection.execute(q, function(err, rows, fields). You're mixing async/await and error-first callbacks. Use one or the other. You probably want to do something like: const rows = await connection.execute(q). – Nik Kyriakides 57 mins ago