Home » Javascript » What is the correct way to be using the Node.js MySQL Library?

What is the correct way to be using the Node.js MySQL Library?

Posted by: admin August 19, 2018 Leave a comment

Questions:

Currently I am playing around with the MySQL library in Node.js however I have a question about the correct/most efficient way to be using this library.

According to w3schools the correct way to make a single query is to use code like this

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
  });
});

However, say I wanted to make multiple queries which would be executed by an event for example how would I handle this? Should I create an “initialise” function which is executed as soon as the program runs such as this?

var mysql = require('mysql');

var database;

//Initialise database
function setupDatabase() {
    database = mysql.createConnection({ 
        host: token.host,
        user: token.user,
        password: token.password,
        database: token.database,
        port: token.port
    });
}

//Imagine this could be called at any time after execution
function event() {
    if(database != null) {
        database.connect(function(err) {
            if (err) throw err;
            database.query("SELECT * FROM customers", function (err, result, fields) {
                if (err) throw err;
                console.log(result);
            });
        });
    }
}

And also do I have to connect to the database each time I make a query or can I add the “database.connect” call to my setupDatabase function such as this?

var mysql = require('mysql');

var database;

//Initialise database
function setupDatabase() {
    database = mysql.createConnection({ 
        host: token.host,
        user: token.user,
        password: token.password,
        database: token.database,
        port: token.port
    });

    if(database != null) {
        database.connect(function(err) {
            if (err) throw err;
        });
    }
}

//Imagine this could be called at any time after execution
function event() {
    if(database != null) {
        database.query("SELECT * FROM customers", function (err, result, fields) {
            if (err) throw err;
            console.log(result);
        });
    }
}

My main concern is that calling the con.connect function every single time I make a query would be slow and although these are asynchronous I want to be using the correct/most efficient way possible. Feel free to correct me on any mistakes with the last two code snippets I have only tested the first one so far.

Answers: