Writing multiple sql queries in nodejs - mysql

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.

Related

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.

Receive data from multiple tables [Nodejs,MySQL]

What do I need to do to get data from multiple tables?
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
connection.connect(function(){
console.log("MySQL Database is Connected");
});
app.use(express.static(__dirname + '/css'));
app.use(express.static(__dirname + '/js'));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.get('/',function(req,res){
res.render('index.html');
});
app.get('/load',function(req,res){
connection.query("select * from terms WHERE status = 1",
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});
});
app.listen(7001,function(){
console.log("App is started at PORT 7001");
});
With this I can only get data from the terms table. But I need to get data from the impTerms table.
How do I get this?
Thank you
Use sql join in query , has nothing to do with node js.
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT terms.id, terms.name FROM terms JOIN impTerms ON impTerms.id= terms.id and terms.status=1";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
There are several ways you can do,
Passing two sql queries to connection
Var sqlQuery = "select * from terms WHERE status = 1;select * from impTerms";
connection.query(sqlQuery,
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});
Output:
[
[], // array of object for terms
[] // array of object for impTerms
]
Changing select query
Var sqlQuery = "select a.*, b.* from a.terms, b.impTerms";
connection.query(sqlQuery,
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});

Node-mysql not working properly... need debug ideas

I am using node-mysql for the first time, and I have a program with no errors, no warnings, but is not working properly... Here is the code for the program, very simple:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database: 'nodetest',
port: 8080
});
connection.connect();
var usr = "BLASHDASD"
var userId = usr;
var sql = 'UPDATE userlist SET user1= ' + connection.escape(userId) + ' WHERE id=1 ';
console.log(sql);
connection.query('sql', function(err, rows, fields) {
console.log(err);
console.log("BLAHSDBKASD");
});
connection.end();
And here is the console output:
C:\wamp\www\nodePHP-master\js>node nodeTest.js
UPDATE userlist SET user1= 'BLASHDASD' WHERE id=1
But nothing is happening in my MySQL table... I even copied and pasted the UPDATE line above and just ran it as SQL code and it worked great... Need some ideas of what is going on. Thanks a bunch
EDIT:
Answered my own question... was listening on wrong port, so connection was failing. Here is updated code for those interested/search in the future:
//TEST
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database: 'nodetest',
port: 3306,
});
connection.connect(function(err){
if(err) {
console.log(err)
} else {
console.log("connected");
}
});
var usr = "BLASHDASD"
var userId = usr;
var sql = 'UPDATE userlist SET user1= ' + connection.escape(userId) + ' WHERE id=1 ';
console.log(sql);
connection.query(sql, function(err, rows, fields) {
console.log(err);
});
connection.end();
You are having problems with node's asynchronous nature, a very common issue when coming to Node. You also had a small but significant error in your code (you have 'sql' as a quoted string), but here is something structurally similar that should point you in the right direction.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'locahost',
user : 'foo',
password : 'bar',
database : 'test'
});
// the callback inside connect is called when the connection is good
connection.connect(function(err){
var sql = "select 'Joe' as name from dual";
connection.query(sql, function(err, rows, fields) {
if (err) return console.log(err);
// you need to end your connection inside here.
connection.end();
console.log(rows[0].name);
});
});
You will likely start wondering about ways to avoid all these callbacks. You may wish to look at my answer to this question for a more extended mysql example as well as an alternative implementation which offers an alternative to callback-mania.

Nodejs - Express - Mysql: render view after post

I am using express to insert/list some records from a mysql db. Everything works fine (insert/select) but how do I render the list function after insert was completed? Do I have to re-invoke the select statement?
var mysql = require('mysql');
exports.create = function(req, res) {
var connection = mysql.createConnection({user: 'root', password: 'password', database: 'test'});
connection.query('INSERT INTO wall (message) VALUES ("' + req.body.message + '")', function(err, result) {
if (err)
throw err
// is this correct? <===
connection.query('SELECT * FROM wall', function(err, rows) {
if (err)
throw err
if (rows)
res.render('wall', {title: 'Wall', data: rows});
});
// end
connection.end();
});
};
exports.list = function(req, res) {
var connection = mysql.createConnection({user: 'root', password: 'password', database: 'test'});
connection.query('SELECT * FROM wall', function(err, rows) {
if (err)
throw err
if (rows)
res.render('wall', {title: 'Wall', data: rows});
});
connection.end();
};
Yes, you do have to SELECT again, and your code is generally correct. I would refactor the common part between list and the part you're asking about, I would not list users and passwords in source files, and make other minor modifications, but generally it's correct.
I read the docs more carefully and i found
res.redirect();
so for my example, it works just fine to do
res.redirect('/wall');
to make a GET request to /wall route. The data will come as this route fetching the list of messages. Thats ok for me.