SQL Server multiple database nodejs connection - mysql

I want to connect to SQL Server where I have few databases. I am using mysql library for nodejs. What I want to achieve is to connect to SQL Server and query different databases based on send query like this.
SELECT * FROM db1 where id = 1
SELECT * FROM db2 where id = 2
etc
My code:
const express = require('express')
const mysql = require('mysql')
const fs = require('fs');
const app = express()
const db = mysql.createConnection({
host: '',
user: '',
password: '',
database: '' // I want to pass db name in SQL query below not here
})
db.connect()
app.get('/', (req, res) => {
//and here i want to pass db name in query not in above.
//so every query that i send will contain db
const sql = 'SELECT * FROM users'
db.query(sql, (err, result) => {
if (err) throw err;
res.json(result)
})
})
app.listen(5000, () => {
console.log('Server started')
})

You can just omit the database attribute in the createConnection object.
See Establishing connections
...
const db = mysql.createConnection({
host: '',
user: '',
password: ''
})
db.connect()
...

Related

Express taking forever to load mySQL query?

I'm trying to query a single line from a 28k record database as a test but it isn't going through but when I load up 'localhost:3001/api/get' it stays loading, even though my connection says success? Is it actually even connecting to the db?
my data bases schema is:
id | state_name | city
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended:true}));
app.get('/api/get', (req, res)=>{
const sqlGet = "SELECT city FROM state_city city = 'Chicago'";
db.query(sqlGet, (err, res)=>{
console.log("success");
});
});
app.listen(3001, ()=>{
console.log("running on port 3001");
});
First you must make server running. Remove that API route you had set before running server.
app.listen(3001, ()=>{
console.log("running on port 3001");
});
Now you must create database connection. Create new file dbconn.js
var mysql = require('mysql');
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "password",
database: "states_city"
});
Now create new connection:
var new_connection = mysql.createPool(
db
);
new_connection.on('connection', function (connection) {
console.log('DB Connection established');
connection.on('error', function (err) {
console.error(new Date(), 'MySQL error', err.code);
});
connection.on('close', function (err) {
console.error(new Date(), 'MySQL close', err);
});
});
// export connection
module.exports = new_connection;
Include that connection in other file:
var db_connection = require('../dbconn');
db_connection.query(query, params, function (error, results, fields) {
//Do your query
});
Read about project structure to make your code easy to edit.

Data not stored in the MySQL database

I'm connecting node backend to MySQL database. When I try to add data, I'm getting a success message, but it's not getting added. Interesting part is that, initially it worked (just once), but now it's not storing the information in the database.
const mysql = require('mysql');
const express = require('express');
const bodyparser = require('body-parser');
const app = express();
app.use(bodyparser.json());
const mysqlconnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'customerdb',
multipleStatements: true
})
mysqlconnection.connect((err) => {
if (!err) console.log('DB Successfully Connected !')
else
console.log('Database Not Connected \n Error' + JSON.stringify(err));
})
app.listen(3000, (req, res) => {
console.log("Server Running on Port 3000");
})
// Insert a customer
app.post('/customers', (req, res) => {
let data = req.body;
var sql = "SET #id = ?;SET #firstname = ?;SET #lastname = ?;SET #password = ?; \
CALL CustomerAddOrUpdate(#_id,#_firstname,#_lastname,#_password);";
mysqlconnection.query(sql, [data.id, data.firstname, data.lastname, data.password], (err, rows, fields) => {
if (!err)
res.send(rows)
else
res.send(err);
})
})
It sounds interesting.
If it worked once and the API always succeed, maybe CustomerAddOrUpdate mysql function was not written correctly.
I would do this:
var sql = "INSERT INTO table (field1, field2, ...) VALUES (value1, value2, ...)";
Can't tell you what is the problem with your code, because it looks fine to me.

Connect MySQL database with node JavaScript application

I make a node JavaScript app and deploy it on cPanel using SSH.
App is working fine without database but when I connect the app with database on cPanel (GoDaddy) it takes times and shows the message "Error establishing a database connection".
My connection code
const mysql = require('mysql');
const express = require('express');
const app = express();
var pool = mysql.createConnection({
host: 'localhost',
user: '<MY_USER_NAME>',
password: '<MY_PASSWORD>',
database: '<DB_NAME>'
});
pool.connect(function(err) {
if (err) throw err;
else{
console.log("Connected!");
}
});
module.exports = pool;
route where DB interact,but lost the connection.
app.post('/loginn', (req, res) => {
var id = req.body.id
console.log("user_id= "+id);
var sql = "select * from users where id NOT IN ('" + id + "') ";
pool.query(sql, function (err, rows) {
if (err) throw err;
else {
res.render('allusers', {
users: rows,
user_id:id
})
}
});
});
This answer is going to take the form of a debugging journey, because that's the only way I can see to get to the bottom of your issue.
Let's do a dead-simple representation of your app to make sure that you can send a query to MySQL and receive a response from a route-handler in Express. Setup your app like this:
const mysql = require('mysql');
const express = require('express');
const app = express();
const PORT = // define the PORT for your host
var connection = mysql.createConnection({
host: 'localhost',
user: '<MY_USER_NAME>',
password: '<MY_PASSWORD>',
database: '<DB_NAME>'
});
connection.connect(function(err) {
if (err) console.error(err);
console.log("Connected!");
});
app.get('/db-test', (req, res, next) => {
var id = // fill in a user_id that you know exists
var sql = `SELECT * FROM users WHERE id NOT IN ('${id}') `;
console.log(sql); // confirm you are sending the sql request you believe you should be sending
connection.query(sql, function (err, results, fields) {
if (err) console.error(err);
console.log(`results: ${results}\nfields: ${fields}`);
});
});
app.listen(PORT);
And then hit the route /db-test from your app, and see what happens. If this works, then we will have at least proved that you CAN make requests between Express and MySQL. Right now, I'm not sure you can, so I'm not sure what to debug.

Send ExpressJS MySql query response to a simple JS file to edit HTML table

i'm using ExpressJS as server, and MySql as local db.
I need to get some data from a table and send the query result to a vanilla JS file or just edit HTML trought NodeJS, but i don't know how...
My Express server:
const express = require("express");
const app = express();
const path = require("path");
app.use(express.static("../public"));
app.get("/home", function(req, res) {
res.sendFile(path.join(__dirname + "/../index.html"));
});
1- To query from your database tables, you'll need to use a Node.js MySQL client or an ORM, I use mysql in the following example:
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
2- Write your query and send back the results to the end-user
const express = require('express');
const router = express.Router();
router.get('/home', function(req, res, next) {
connection.query('SELECT * FROM `tablename`;', function (error, results, fields) {
if (error) throw error;
res.send({ results });
});
});
You have to choose a template engine like pug
You should connect to your database as mentioned before :
const mysql = require('mysql');
const connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
and make your query form your TableName :
const express = require('express');
const router = express.Router();
router.get('/home', function(req, res, next) {
connection.query('SELECT * FROM `tablename`;', function (error, results, fields) {
if (error) throw error;
res.render('index', { 'data' : results })
});
});
And for your template page :
ul
each val, index in data
li= index + ': ' + val

Writing multiple sql queries in nodejs

I want to display all the values from two tables from my database and display it as console.log. If I write a single query in var sql and display it as console.log(results) it works but not for multiple queries.
var express = require('express');
var app = express();
let mysql = require('mysql')
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pitch_perfect_db2',
multipleStatements: true
})
app.get('/',(req, res) => {
connection.connect();
var sql = 'SELECT * FROM investors?; SELECT * FROM member_info?;'
connection.query(sql, function(err, results, fields){
if (!err) {
// res.send(JSON.stringify(results[0]));
// res.send(JSON.stringify(results[1]));
console.log('hey');
//console.log(results);
console.log(results[0]);
console.log(results[1]);
} else{
console.log('Error while performing query.');
}
});
connection.end();
})
//app.listen(port, () => console.log('Server Started pn port ${port}'));
app.listen(3002);
I was able to get it to work but I had to do 2 things:
First I renamed the tables to remove the question mark as it was always getting translated to a '1' and the table name no longer matched what was in the DB.
Second, I added an array to the connection.query(). After that it worked just fine.
More info here
var express = require('express');
var app = express();
let mysql = require('mysql')
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pitch_perfect_db2',
multipleStatements: true
})
app.get('/',(req, res) => {
connection.connect();
var sql = 'SELECT * FROM investors; SELECT * FROM member_info;';
//var sql = 'SELECT * FROM investors;';
connection.query(sql, [1, 2], function(err, results, fields){
if (!err) {
res.send(JSON.stringify(results[0]) + JSON.stringify(results[1]));
console.log('hey');
//console.log(results);
console.log(results[0]);
console.log(results[1]);
} else{
console.log('Error while performing query.');
console.log(err);
}
});
connection.end();
})
//app.listen(port, () => console.log('Server Started pn port ${port}'));
app.listen(3002);
In node you don't use ; in your sql statements. Assuming both the investors and member_info tables have the same number of columns, you will need to use this:
var sql = 'SELECT * FROM investors UNION ALL SELECT * FROM member_info';
Alternatively, if investors and member_info are unrelated tables, you will need to journey into callback hell to get what you need:
app.get('/',(req, res) => {
connection.connect();
var sql1 = 'SELECT * FROM investors';
var sql2 = 'SELECT * FROM member_info?';
connection.query(sql1, function(err, investors){
if (err) throw err; //you should use this for error handling when in a development environment
console.log(investors); //this should print
connection.query(sql2, function(err, members) {
if (err) throw err;
console.log(members);
res.render('your view', {investors:investors, members:members});
});
});
});
If you decide on the latter approach, I would urge you to reconsider your database layout.
If either of the tables in your examples have a foreign key relation with each other, you should definitely be using some kind of JOIN statement on these tables, instead of a UNION.