In my project, I am using MySQL database. The problem is, that I don't know how to write simple database module to one js file.
My code is:
File: database.js
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
module.exports = class Database {
constructor() {
connection.connect(function (err) {
if (err) {
console.error(err);
throw err;
} else {
console.log("Connection to database was successful");
}
});
}
getConnection() { return connection; }
};
I have a lot of files in project and each one needs use database, the problem is, when I import database.js constructor is every time called, I think, its a bad way.
Is there any better way how to use database connection in project? Somethink like call getConnection() from database.js file without call constructor.
Thank you for any help.
A possible solution:
const mysql = require("mysql"),
connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "mydb"
});
connection.connect(function (err) {
if (err) {
console.error(err);
throw err;
} else {
console.log("Connection to database was successful");
}
});
module.exports = {
getConnection() { return connection; }
};
In your database.js file while exporting write:
modules.exports = new Database();
And use
require('./path/to/database-file')
Wherever you have to use the instance, It will always get the same object.
Related
I wrote this script to connect to my local DB with mssql and node.js.
Here is my "server.js" script:
const sql = require(‘mssql’);
//write the configuration to connect to our database:
var config = {
user: ‘root’,
password: ‘’,
server: ‘localhost’,
database: ‘testangular’
};
sql.connect(config, function(err) {
if (err) { console.log(‘Connect err: ‘ + err); return; }
isConnected = true;
});
When I run it I get this syntax error:
screenshot
I'm kind of new to javascript, so it might be a ridiculous mistake, but your help will be appreciated!!
That is probably because You're using apostrophes. You should not use ‘ and ’ but ' or ".
const sql = require('mssql');
// write the configuration to connect to our database:
var config = {
user: 'root',
password: '',
server: 'localhost',
database: 'testangular'
};
sql.connect(config, function(err) {
if (err) { console.log('Connect err: ', err); return; }
isConnected = true;
});
Tip: I also suggest using semicolon here, in case err is an object.
console.log('Connect err:', err);
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.
You have to make database connection only once per application livetime (unless you have disconnects). Then you may have as much queries as you want.
Just put database connection routine somewhere in sepparate file and then require it in your applicatin initialisation step.
// mysql.js
const mysql = require('mysql');
module.exports = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
Or require it anywhere you need database connection - it will return connected database object without reruning that code again and again.
// inex.js
const databse = require('./mysql')
database.query("SELECT * FROM customers")
I created a file which include a function that holds a pool and handles the connection to the database like this
let _this = {};
let POOL = null;
function getPool() {
return new Promise((resolve, reject) => {
if(POOL != null) {
resolve(POOL);
} else {
//create connection pool
POOL = connectionPool;
resolve(POOL);
}
});
}
function closePool(){
// close pool here
}
_this.getPool = getPool;
_this.closePool = closePool;
module.exports = _this;
Now you can call getPool() and will recive a pool of connections where you can execute your queries with.
I'm using the mysql module in Node.js. In my model file, currently, I'm specifying the connection constants in each method. However, this is taking up a lot of space and I know it's not ideal.
Here's what that looks like.
doSomething: () => {
var connection = mysql.createConnection({
host : config.database.host,
database : config.database.database,
user : config.database.user,
password : config.database.password
});
connection.query( ... );
connection.destroy();
},
doSomethingElse: () => {
var connection = mysql.createConnection({
host : config.database.host,
database : config.database.database,
user : config.database.user,
password : config.database.password
});
connection.query( ... );
connection.destroy();
},
Could anyone recommend a way to tidy things up a bit and reduce the redundant code here?
Create the connection once and pass it to module exports.
const mysql = require("mysql");
const conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "db"
});
module.exports = conn;
Then you can import it in other files and use it.
var dbConnection = require('./dbConnection');
dbConnection.query();
However, instead of using createConnection, I recommend using createPool instead.
Connections can be pooled to ease sharing a single connection, or
managing multiple connections.
const mysql = require("mysql");
const conn = mysql.createPool({
host: "localhost",
user: "root",
password: "",
database: "db"
});
module.exports = conn;
You can use it like this. Make sure to release the connection after fetching data from the table:
var connectionPool = require('./dbConnection');
connectionPool.getConnection((err, connection) => {
connection.query('SELECT * FROM table', (error, result) {
connection.release();
if(error) throw error;
});
});
To close all connections in the pool:
connectionPool.end(function (err) {
// all connections in the pool have ended
});
I'm trying to use connection from a connection.js file and use it in different file webFrontend.js using exports object. Now what I get on running server is:
{
"Result": "undefinedThis is result"
}
That means connection is not defined. Why is it happening? connection is working fine if getConnection is created in same (webFrontend.js) file, but the problem is when I use getConnection in same exports function in connection.js hence the connection not defined error:
Here are 2 necessary files (routes file has no problem) that explains what I'm doing:
connection.js
var mysql = require('mysql');
exports.connExport = function () {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
if(connectionPool) {
connectionPool.getConnection(function (err, connection) {
if (err) {
return err;
} else {
return connection;
}
});
}else{
var abc="return error";
return abc;
}
}
webFrontend.js
var connObj=require('../Routes/connection.js');
var connection=connObj.connExport();
exports.getIndivRecords= function(req, res, next){
res.send({
Result: connection+"This is result"
});
return next();
};
No need for the .js file extension, it's automagically added for you.
The code below uses standard error-first callbacks
webFrontend.js
var connection = require('../Routes/connection');
exports.getIndivRecords = function(req, res, next){
// connection takes a standard error-first callback
connection(function(err, conn){
if (err) {
// Handle the error returned
console.log(err);
}
// The database connection is available here as conn
console.log( "Connection:" + conn);
// presumably you want to do something here
// before sending the response
res.send({
Result: conn + "This is result"
});
});
return next();
};
connection.js
var mySQL = require('mysql');
var connectionPool = mySQL.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
var getConnection = function (cb) {
connectionPool.getConnection(function (err, connection) {
// pass the error to the callback
if (err) {
return cb(err);
}
cb(null, connection);
});
};
module.exports = getConnection;
First of all #Dan Nagle was right no need of .js
Second You are getting the connection undefinded because still the method doesnt returned with result.
Use promise to call your Connection.js method
Your node is single threaded async execution,
He doest wait for the method to return a result
1) Problem with your javascript is that
var connection=connObj.connExport();
in Creation stage connection was defined by javascript as undefined and as
connObj.connExport(); as still not returned with answer
it executed this function in which connection was undefined
exports.getIndivRecords= function(req, res, next){
res.send({
Result: connection+"This is result"
});
Use promise read this first so you can understand something about promise and callback if you are unable to solve than comment i will play with it.But first you try.Thanku
Understanding promises in node.js
Ok Try This I have used promise here
var connObj = require('../Routes/connection');
connObj.connExport().then(
function (connection) {
exports.getIndivRecords = function (req, res, next) {
res.send({
Result: connection + "This is result"
});
return next();
};
}).catch(function (err) {
res.status(400).send(err);
return;
});
var mysql = require('mysql');
exports.connExport = function () {
return new Promise(function (fulfill, reject) {
var connectionPool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'rockcity_followme'
});
if (connectionPool) {
connectionPool.getConnection(function (err, connection) {
if (err) {
return reject(err);
} else {
return fulfill(connection);
}
});
} else {
var abc = "return error";
return reject(abc);
}
});
}
I want to connect to different databases on server side so I can perform queries that include those two databases using node.
I have a config.js like this:
module.exports = {
database: {
user: 'brunojs',
password: 'bdpf5',
connectString: 'localhost:1521/orcl'
},
jwtSecretKey: "jmvhDdDBMvqb=M#6h&QVA7x"
};
This saves my info for accessing the first database.
Then I have one list.js file which performs the query:
var oracledb = require('oracledb');
var jwt = require('jsonwebtoken');
var config = require(__dirname + '../../config.js');
function get(req, res, next) {
oracledb.getConnection(
config.database,
function(err, connection){
if (err) {
return next(err);
}
connection.execute(
'select num_sequencial, notes, des_especialidade, dt_diag ' +
'from organite_repository ',
{},//no binds
{
outFormat: oracledb.OBJECT
},
function(err, results){
if (err) {
connection.release(function(err) {
if (err) {
console.error(err.message);
}
});
return next(err);
}
res.status(200).json(results.rows);
connection.release(function(err) {
if (err) {
console.error(err.message);
}
});
}
);
}
);
}
module.exports.get = get;
Everything works fine.
The thing is, right now, I want to perform queries using another database. How can I do that?
the right solution is to use pool https://github.com/oracle/node-oracledb/blob/master/doc/api.md#createpool
Creating massive pool:
module.exports = {
database: [{user: 'brunojs',
password: 'bdpf5',
connectString: 'localhost:1521/orcl',
poolAlias:'database1'
},
{user: 'brunojs',
password: 'bdpf5',
connectString: 'localhost2:1521/orcl',
poolAlias:'database2'
}],
jwtSecretKey: "jmvhDdDBMvqb=M#6h&QVA7x"
};
during initialization web-server, initialize the pools
const dbConfig = require('../config/database.js');
async function initialize() {
dbConfig.database.forEach(async function(item) {
const pool = await oracledb.createPool(item);
});
}
Then you can use the created pools when calling the connection procedure:
conn = await oracledb.getConnection('database1');
const execresult = await conn.execute(context.execsql, execbinds, context.opts);
First, add a second credentials object in your config.js
module.exports = {
database: {
user: 'brunojs',
password: 'bdpf5',
connectString: 'localhost:1521/orcl'
},
database2: {
user: 'user2',
password: 'password',
connectString: 'someotherhost:1521/orcl'
},
jwtSecretKey: "jmvhDdDBMvqb=M#6h&QVA7x"
};
then use one or other here:
oracledb.getConnection(
config.database, // you could change this line to config.database2
function(err, connection){
if (err) { ...
If you want to query one database, then another, you'd need to keep references to both connection objects (error checking omitted for brevity):
oracledb.GetConnection(
config.database,
function(err, connection1) {
oracledb.GetConnection(
config.database2,
function(err, connection2) {
// in this function you can use either connection object
connection1.execute(...);
connection2.execute(...);
}
});
This is slightly out of scope for your question, but you could also take a look at Waterline. It supports setting up multiple databases and then tying models to them, so that knowing where certain data models are stored is abstracted away.
you can always use links on the DB side, so your java code does not have to connect to another DB, for example:
select num_sequencial, notes, des_especialidade, dt_diag
from organite_repository#linkA
UNION
select num_sequencial, notes, des_especialidade, dt_diag
from organite_repository#linkB
/* ... */