Shujin
Shujin

Reputation: 37

Creating a global sql function

I'm new to javascript and need to know how to create a global function or class that can access by every other page on the website when it is required

mysqlConnection.js

function mysql.connection () {
  const mysql = require('mysql');

  const con = mysql.createConnection({
     host: "hostname",
     user: "username",
     password: "password",
     database: "database",
  });
};

script.js

mysql = require('mysqlConnection.js');
mysql.connection();
con.connect(function (err) {
  if (err) throw err;

  // Query
  con.query(sql, function (err, result) {
    if (err) throw err;
    // Result
  });
});

Upvotes: 0

Views: 316

Answers (1)

David
David

Reputation: 1174

Use module.exports

Then you could do it like this:

/* config.js */ 

const mysql = require('mysql');

const configDB = mysql.createConnection({
  multipleStatements: true,
  port: 3306,
  host: 'XXXXX',
  user: 'XXXXX',
  password: 'XXXXX',
  database: 'XXXXX',
});

module.exports = configDB;

Then you simply import it to each file where you need it:

/* main.js */

const configDB = require('./config.js');

configDB.query(query, (err, data) => {
 (....)

Upvotes: 1

Related Questions