save result of MySql query in variable using node js - mysql

I want to know how can I save result of MySql query in variable using node js
I used this to connect to mysql and get query
var mysql = require('mysql');
var express = require('express');
var app = express();
app.get('/informations', function (req, res) {
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'root',
password : '',
database : 'dbUsers',
}
);
connection.connect();
var queryString = 'SELECT * FROM hpform';
connection.query(queryString, function(err, rows, fields) {
res.json(rows);
for (var i in rows) {
console.log('NomBase: ', rows[i].NomBase);
console.log('CheminHP: ', rows[i].CheminHP);
console.log('Chemin: ', rows[i].Chemin);
console.log('HPuser: ', rows[i].HPuser);
console.log('pass: ', rows[i].pass);
console.log('path_pub: ', rows[i].path_pub);
}
});
connection.end();
});
module.exports = app;
and I have this in result:
[{"HPId":16,"NomBase":"Base","CheminHP":"C:\\Program Files (x86)\\Hewlett-Packard\\HP Exstream\\HP Exstream 9.5.102","Chemin":"P:\\\\EXSTREAM\\\\BASES\\\\MACSF_DB_EditiqueV9.5.accdb","HPuser":"admin","pass":"admin","path_pub":"D:\\Users\\hbenkhal\\Desktop\\essaipub"},{"HPId":21,"NomBase":"LMG","CheminHP":"C:\\Program Files (x86)\\Hewlett-Packard\\HP Exstream\\HP Exstream 9.5.102","Chemin":"D:\\\\hp_LMG\\\\BaseAccess20160330.accdb","HPuser":"admin","pass":"admin","path_pub":"D:\\Users\\hbenkhal\\Desktop\\essaipub"},{"HPId":22,"NomBase":"Meriem","CheminHP":"C:\\Program Files (x86)\\Hewlett-Packard\\HP Exstream\\HP Exstream 9.5.102","Chemin":"D:\\base_meriem\\Test.accdb","HPuser":"admin","pass":"admin","path_pub":"D:\\Users\\hbenkhal\\Desktop\\essaipub"},{"HPId":24,"NomBase":"bouygues","CheminHP":"C:\\Program Files (x86)\\Hewlett-Packard\\HP Exstream\\HP Exstream 9.5.102","Chemin":"D:\\\\hp_LMG\\\\bouygues\\\\20160425 - PRODUCTION MEP FE_22606 - Ano314002 Libellé remboursement EDP Appro","HPuser":"admin","pass":"admin","path_pub":"D:\\Users\\hbenkhal\\Desktop\\essaipub"},{"HPId":26,"NomBase":"hamza","CheminHP":"C:\\Program Files (x86)\\Hewlett-Packard\\HP Exstream\\HP Exstream 9.5.102","Chemin":"P:\\\\EXSTREAM\\\\BASES\\\\MACSF_DB_EditiqueV9.5.accdb","HPuser":"admin","pass":"admin","path_pub":"D:\\Users\\hbenkhal\\Desktop\\essaipub"}]
now I want to save my results as a request to use them in exec command something like this
child = exec("\"" + req.session.CheminHP + "/Packager.exe\" -APPLICATION=" + req.params.app + " -ACCESSDB=" + req.session.Chemin + " -EXSTREAMUSER=" + req.session.HPuser + " -EXSTREAMPASSWORD=" + req.session.pass + " -PACKAGEFILE=" + req.session.path_pub + "\\" + req.params.app + ".pub", function (error, stdout, stderr)
Can I have a suggestion to do this.
Thank you.

If you get only one row from your query try this:
connection.query(queryString, function(err, rows, fields) {
res.json(rows);
var elem = rows[0];
for (var prop in elem) {
req.session[prop] = elem[prop];
}
});
connection.end();

Thank you very much Nikita Namestnikov.
I used what you tell me to do and I add
console.log('NomBase: ' + req.session.NomBase);
console.log('CheminHP: ' + req.session.CheminHPBase);
console.log('Chemin: ' + req.session.CheminBase);
console.log('HPuser: ' + req.session.HPuserBase);
console.log('pass: ' + req.session.passBase);
console.log('path_pub: ' + req.session.path_pubBase);
to see if that work but there is a problem
When I Use req.session.NomBase, req.session.CheminHPBase,... in my routes it undefined

Related

Nodejs with mysql query not giving dynamic value from database

I am trying to upload a file in two location, it is working find when I am testing it from postman. But when we trying to upload file from my mobile app without it return an error.
one interesting thing: when after restarting server if we first hit from postman then it is working from mobile app as well but in that case dynamic value to not updating, Value came from postman hit is used in dynamic field.
// app.get('/empid/:id', (req, res) => {
app.post('/upload/:id', function(req,res){
pool.query('SELECT first_name, username FROM user_detail where user_detail_pk=?', [req.params.id], (err, rows, fields) => {
if (!err)
res.send(rows);
else
console.log(err);
rows.forEach( (row) => {
console.log(`${row.first_name}`);
var fname = (`${row.first_name}`);
var username = (`${row.username}`);
console.log('First Name is : ' + fname);
console.log('UserName Name is : ' + username);
var dateObj = new Date();
//var month = dateObj.getUTCMonth() + 1; //months from 1-12
var year = dateObj.getUTCFullYear();
var month = dateObj.toLocaleString('default', { month: 'long' });
var day = dateObj.getUTCDate();
datewise = "datewise" + "/" + year + "/" + month + "/" + day + "/" + fname + "(" + username + ")";
empwise = "empwise" + "/" + fname + "(" + username + ")" + "/" + year + "/" + month + "/" + day;
});
var storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
let datewisepath = `/home/KunDan/RestAPIUpload/Conveyance/${datewise}`;
let empwisepath = `/home/KunDan/RestAPIUpload/Conveyance/${empwise}`;
fs.mkdirsSync(datewisepath);
fs.mkdirsSync(empwisepath);
cb(null, datewisepath);
cb(null, empwisepath);
// callback(null, 'uploads/' + req.user.id);
},
/* filename: function (req, file, callback) {
callback(null, file.originalname + '-' + Date.now());
}
});
*/
filename: function (req, file, cb) {
console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.originalname + '-' + Date.now() + "." + extension);
console.log(req.file);
}
})
var upload = multer({ storage : storage }).array('dataFile',50);
upload(req,res,function(err) {
console.log(req.body);
console.log(req.files);
if(err) {
return res.end("Error uploading file.");
}
//return res.end("File is uploaded");
else
("File is uploaded");
});
});
});
Error Screenshot is Here

Social Signup testing using Protractor & mysql

I am trying to test the signup process for Social sites [google,Linkedin & Facebook] which will run concurrently using same MailId.In mysql DB,I run Queries inside the beforeLaunch:function() in CONFIG file.What is the other approach to tackle the ID=undefined issue when it executes DELETE query from DB?
Config.js file >
beforeLaunch:function(){
var ConnectDatabase = require('../dbconnections/ConnectDatabase.js');
var connectDatabase = new ConnectDatabase();
connectDatabase.connection.connect();
// checking id for created user
var sql = 'SELECT id FROM users where email='+ '\'quantra.learner#gmail.com\'';
var userID = connectDatabase.connection.query(sql,function(err, result){
if (err) {
console.log(err);
} else if (result[0].id == 'undefined' || result[0].id == 'null') {
console.log('This user is not available');
}else {
console.log('Find User ID by email : ' +result[0].id);
}
// deleting id for created user from 2 DB tables
var sql1 = 'DELETE FROM user_details WHERE user_id='+result[0].id;
var query1 = connectDatabase.connection.query(sql1,function(err, result1) {
if (err) console.log(err);
console.log('User_details Table : user_id '+ result[0].id + ' deleted!');
console.log('affectedRows: ' + result1.affectedRows);
var sql2 = 'DELETE FROM users WHERE id=' + result[0].id;
var query2 = connectDatabase.connection.query(sql2,function(err, result2) {
if (err) console.log(err);
console.log('Users Table : id ' + result[0].id + ' deleted!');
console.log('affectedRows: ' + result2.affectedRows);
});
});
});
},
Getting error > Cannot read property 'id' of undefined

node mysql cannot access property

Having some trouble parsing the results returned from a node "mysql" query.
Node version 7.8.0
Running CentOS AWS environment.
I developed the node app in Windows Visual Studio CE 2017, and it was working fine, but when porting it to Linux, it's not actually allowing me to access the user_id variable within the results.
I have included lots of variations in trying to access the variable, however the correct one I believe should be:
rows[i].user_id
All the others are just there as a reference to show that they don't work.
Code:
'use strict';
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mysql = require("mysql");
var con = mysql.createConnection(dbConfig);
con.connect(function (err) {
if (err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
var q = "select * from table";
con.query(q, function (err, rows) {
for (var i = 0; i < rows.length; i++) {
var row = JSON.stringify(rows[i]);
var rowParsed = JSON.parse(row);
console.log(row);
console.log(" row[0].user_id " + row[0].user_id );
console.log(" row.user_id " + row.user_id );
console.log(" parsed " + JSON.parse(row));
console.log(" rowParsed.user_id " + rowParsed.user_id);
console.log(" rowParsed['user_id'] " + rowParsed['user_id']);
console.log(" rows[i].user_id " + rows[i].user_id)
console.log(" rows[i]['user_id'] " + rows[i]['user_id']);
console.log(rows[i]);
}
});
Results:
Connection established
[{"user_id":2}]
parsed [object Object]
row[0].user_id undefined
row.user_id undefined
rowParsed.user_id undefined
rowParsed['user_id'] undefined
rows[i].user_id undefined
rows[i]['user_id'] undefined
[ RowDataPacket { user_id: 2 } ]
POST /users/register 200 120.026 ms - 22

Nested mysql query in each loop

So all i want to do is to make a query to get all id's from the database and then i want to do my method for the id and update the row in the database.
So i created this code. But all it is doing is to get the ids and do not the nested query with the insertString1.
var mysql = require('mysql');
var _ = require("underscore");
var connection = mysql.createConnection({
host : 'myHost.net',
user : 'myUser',
password : 'myPassword',
database : 'myDatabase'
});
connection.query('SELECT * FROM `idmarkethash`', function (error, results) {
_.each(results, function (row) {
// here i want to calculate the new values of the row
// This insert query is just an example
var insertString1 = "UPDATE idmarkethash SET " +
"Price=" + mysql.escape(2.00) + ", " +
"Gradient=" + mysql.escape(2.00) + ", " +
"LastUpdated=" + mysql.escape("2015-08-31 00:00:11") + " " +
"WHERE Id=" + mysql.escape(181) + ";";
connection.query(insertString1, function (error1, result1) {
console.log(result1);
});
});
});
I tried the same with the async package:
var async = require('async');
// Packages are all included.
connection.query('SELECT * FROM `idmarkethash`', function (error, results) {
async.each(results, function (row, callback) {
// here i want to calculate the new values of the row
// This insert query is just an example
var insertString1 = "UPDATE idmarkethash SET " +
"Price=" + mysql.escape(2.00) + ", " +
"Gradient=" + mysql.escape(2.00) + ", " +
"LastUpdated=" + mysql.escape("2015-08-31 00:00:11") + " " +
"WHERE Id=" + mysql.escape(181) + ";";
connection.query(insertString1, function (error1, result1) {
console.log(result1);
callback();
});
});
});
With debugging i could see that the declaration of insertString1 is called, but the second query is not fired / or the loop continues without recognizing the second query.

Node.js mysql pool issue

I've started to use pool connection to mysql, instead of using normal connection with Node.js. Because I need to release connection after process has finish. When connection keeps open, Node.js getting in exception due to mysql timeout issue.
I've edited my code and not it gives me error like that in Line 94:
TypeError: Object #<Connection> has no method 'release'
at Query._callback (/usr/local/src/conn.js:94:28)
Above that line :
socket.on('getUnreadPM', function (msg) {
var userSocket = clients[msg.userDestID];
if (msg.lastGotMessage == 'none') {
post = 'Select * from messages where (destUserID=\'' + msg.userDestID + '\' AND srcUserID=\'' + msg.userSrcID + '\') OR (destUserID=\'' + msg.userSrcID + '\' AND srcUserID=\'' + msg.userDestID + '\')';
} else {
post = 'Select * from messages where destUserID=\'' + msg.userDestID + '\' AND srcUserID= \'' + msg.userSrcID + '\' AND messageSendDate between \'' + msg.lastGotMessage + '\' and \'' + msg.deviceCurrentTime + '\' AND messageSendDate > \'' + msg.lastGotMessage + '\' order by messageSendDate';
}
pool.getConnection(function (err, connection) {
// Use the connection
connection.query(post, function (error, results, fields) {
// And done with the connection.
if (results.length > 0) {
if (typeof userSocket !== 'undefined') {
var boolData = results[0];
//console.log('bool data lenght : ',results.length);
var messageID = new Array();
var srcUserID = new Array();
var destUserID = new Array();
var messageContent = new Array();
var messageDate = new Array();
var didRead = new Array();
for (var i = 0; i < results.length; i++)
{
messageID.push(results[i].messageID);
srcUserID.push(results[i].srcUserID);
destUserID.push(results[i].destUserID);
messageContent.push(results[i].messageContent);
messageDate.push(dateFormat(results[i].messageSendDate, "yyyy-mm-dd HH:MM:ss"));
didRead.push(results[i].didRead);
}
userSocket.emit('history :', {
'dataMode': 'history',
'srcUserID': srcUserID,
'destUserID': destUserID,
'messageContent': messageContent,
'messageSendDate': messageDate,
'didread': didRead
});
} else {
userSocket.emit('history :', {
'dataMode': 'none',
});
}
} else {
userSocket.emit('history :', {
'dataMode': 'none',
});
}
connection.release();
});
});
});
The mysql connection has no release method. So you can't release it.
I've written such a node module for my application a few months ago, you can find it here: https://github.com/LinuxDoku/node-mysql-pool
It creates an pool of connections at startup, queues your queries and sends them successive to the database. After getting the result, the connection will be released for new queries.