A
A
Alexander Sharomet2016-07-19 15:38:16
MySQL
Alexander Sharomet, 2016-07-19 15:38:16

How to transfer a database connection to a separate file?

Hello.
Tell me how to make a connection to the database in a separate file in nodejs?
//Db
var mysql= require('mysql');

//database.js
var connection=mysql.createConnection({host:'localhost', user:'root' ,password: '', database : 'nodejs'});
connection.connect(function(err){
    if(!err) {
        console.log("Database is connected ... nn");    
    }else {
        console.log("Error connecting database ... nn");    
    }
});
exports.module=connection;

//file.js
var database= require('database');
database.connection.query('SELECT * FROM users', function(err, rows, fields) {
    if (err) throw err;
        console.log(rows);
});
database.connection.end();

//Как то так. Но такая схема не работает

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2016-07-24
@sharomet

mysqlconfig.js:

module.exports = exports = {
host:'localhost',
 user:'root' ,
password: '',
 database : 'nodejs'
};

well, then
var mysqlConfig = require('mysqlconfig.js');
var connection=mysql.createConnection(mysqlConfig);

if I understand correctly what you are asking

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question