How to create dynamically database connection in Node.js? - mysql

I have created API using express.js framework in Node.js server. My database is mysql. i am able to create connection with database. Below is code for connection.
Now i want to create connection dynamically. I have 2 database ( databaseFirst and databaseSecond).
var mysql=require('mysql');
var connection=mysql.createPool({
host:'localhost',
user:'root',
password:'',
database:'databaseFirst'
});
module.exports=connection;
1) User will login using databaseFirst.
2) After successfully login, they will get database name like as databaseSecond.Now all other APIs will use databaseSecond for that logged user.
3) Each API will send database name so they can identify that which database is using for that user.
Kindly help me.

You can do similar :
Here refrence link : 1.stack 2.documents, nodeDBConnection
var connection;
function createConnectionDB (host,dbName,userName,password) {
connection[dbName] = mysql.createConnection({
host : host,
user : userName,
password : password,
database : dbName
});
connection[dbName].connect();
};
// In API when You getting DBName 'db1' you can use
createConnectionDB('localhost','db1','username','password')
connection['db1'].query('SELECT * from < table name >', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection['db1'].end();
////So API when You getting DBName ('db2') you can use
createConnectionDB('localhost','db2','username','password')
connection['db2'].query('SELECT * from < table name >', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection['db2'].end();

Related

How to fetch data from MySQL to React html table

Is there a way to get data from the MySQL database (this can be done whit the Node.js back-end), but I can not create a table from that data in React.js?
Is there a good option to do that?
(I'm creating an electron application whit react and I want to list all the users from the MySQL database)
In PHP is like this https://www.w3schools.com/php/php_mysql_select.asp
var mysql = window.require('mysql');
function Test() {
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
port : 8889,
database : 'loginsystem'
});
connection.connect();
var sql = 'SELECT * FROM users';
connection.query(sql, function (error, results, fields) {
if(error){
console.log(error);
}
if (!results.length){
console.log("error_fetching_data_from_database --",results.length);
}else{
console.log(result)
}
});
const listof = (
//I want print out useres here like table from the database
)
return(listof)
}
export default Test;

How to make a request in a localhost mysql database

I am using mysql and request. I want to make a request in my localhost server. I just need to know how to make the get request into the localhost server because I don't understand how, I'm running into a continuous loop.
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'virtual_currency_price'
});
Request:
router.get('/getprice', function(req, res){
request(connection, function (error, response, body) {
if (!error && response.statusCode == 200){
}
});
});
I'm trying to figure out how to do this but I'm failing very miserably
The table I'm trying to GET from is called "price" and I will be using the datetime to fetch certain prices.
After you establish a connection with your server you can use it to fetch data from database. You don't need to make a request using the module, just use the connection directly to execute queries as below:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'virtual_currency_price'
});
connection.connect();
connection.query('SELECT * from price', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
});
connection.end();
It's recommended that you create a pool of connections instead and reuse them in your app instead of creating it every time you need to access the DB.
See the docs from github.

How to configure custom database Mysql in Auth0 Connection?

I'm using auth0 as my authentification services into my project. I really love it, but I have a problem when using custom database(MySql), I sure that I have configured the db.connection parameter to my remote shared hosting database in Plesk. It always show : "[Error] Script execution did not complete within 20 seconds. Are you calling the callback function?", When I trying to run "Create" script.
here the script :
function create (user, callback) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '192.168.23.16',
user : 'user',
password : 'pass',
port : '3306',
database : 'dbname' });
connection.connect();
var query = "INSERT INTO users SET ?";
var insert = {
password: bcrypt.hashSync(user.password, 10),
email: user.email
};
connection.query(query, insert, function (err, results) {
if (err) return callback(err);
if (results.length === 0) return callback();
callback(null);
});
}
What should I'm doing right now to solve this problem? I'm new to this
Thanks..
Regards,
fxbayuanggara
You're trying to connect to a local IP address (192.168.23.16), which will always fail since database scripts and rules are executed from Auth0's servers. You'll need to make your MySQL server accessible from Auth0's IP addresses, which at the time of writing are the following:
US domains: 138.91.154.99, 54.221.228.15, 54.183.64.135, 54.67.77.38, 54.67.15.170, 54.183.204.205, 54.173.21.107, 54.85.173.28
EU domains: 52.28.56.226, 52.28.45.240, 52.16.224.164, 52.16.193.66

How to access mysql db from meteor

Is there a way to import data from MySQL database on Meteor startup? I basically need just an initial data from MySQL to export it to Mongo collections for usage.
Your best bet might be to just use a mysql node package (remember to use Meteor.npmRequire(..) instead of require(..)). This one seems good:
https://github.com/felixge/node-mysql
Something like this should work:
if (Meteor.isServer) {
var mysql = Meteor.npmRequire('mysql');
Meteor.startup(function() {
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT * FROM table', function(err, rows, fields) {
if (err) throw err;
// create documents from rows[i] and add to your collection
});
connection.end();
});
}

Node.js changes in mysql

i have a question regarding about node.js for mysql.
I'm trying to check for changes in the database with node.js and every time it does a change it would do something.
I have the following code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
database : 'socialpodd',
});
connection.connect();
connection.query('SELECT * FROM personal', function(err, rows, fields) {
if (err) throw err;
console.log('Rows: ', rows[0].email);
});
connection.end();
But I want this code to be called once there is a change in the database. I know I could do a poll method, but it doesn't seem that effective and real-time. What would be a good real-time module that would allow me to do it, or is polling my only option?