node.js mysql query cannot run due to quotes around digit - javascript

I have this mysql query written in node.js mysql and restify to be executed in a HTTP GET.
https://github.com/felixge/node-mysql
var api_get_func = function (app, url_path) {
function respond(req, res, next) {
var id= req.query.id;
var limit = req.query.limit;
var query_str =
"SELECT table.sw_type, " +
"FROM users " +
"WHERE (id = ?) " +
"LIMIT ?"; //limit
var var_arr = [id, limit];
var query = connection.query(query_str, var_arr, function (err, rows, fields) {}
//SQL query ...
return next();
}
app.get(url_path, respond);
}
The HTTP GET URL is http://127.0.0.1/read_sw?id=51&limit=1
The error reported is that the query is not properly formed. The actual query looks like this;
SELECT table.sw_type,
FROM users
WHERE (id = 51)
LIMIT '1'
I think the problem is LIMIT '1'. I think the solution is to make the query look like this;
SELECT table.sw_type,
FROM users
WHERE (id = 51)
LIMIT 1
How can the node.js code be modified?

This is not about mysql...
Anything in req.query is a string :
How about
var var_arr = [id, parseInt(limit)];

You can also use
var limit = Number(req.query.limit);

Related

Output always gives []

I am trying to filter some data by "averageRating".
This is my code for the method:
filterr(request, respond) {
var averageRating = request.params.rating;
var sql = "SELECT * FROM shopreview.shops WHERE averageRating = ?";
db.query(sql, [averageRating], function (error, result) {
if (error) {
throw error;
}
else {
respond.json(result);
}
});
}
My sql statement is working when I test it against my database. However, I keep getting [] as my result. Can someone please help identify what the problem is? Thanks a lot!
the problem is that "?" since the db is unable to parse it.
either add that avarageRating variable like so:
var sql = "SELECT * FROM shopreview.shops WHERE averageRating = ${parseInt(avarageRating)}";
or if you're using couchbase you could parse it like this:
var sql = `SELECT * FROM shopreview.shops WHERE averageRating = $1`;
where $1 is the first variable in the array of variables.

How to pass mysql query in function and get the results

Hello I have database and queries written in a module and I am calling the module from the main class. What I want is to pass a query in function and get results. This is what I am doing so far
database.js
var pool = mysql.createPool({
host : 'localhost',
user : 'xxxx',
password : 'xxx',
database : 'xxx'
});
exports.executeQuery=function(query,callback){
pool.getConnection(function(err,connection){
if (err) {
console.log("error comes " + err);
callback(true);
return;
}
connection.query(query,function(err,results){
connection.release();
if(!err) {
console.log("no error");
callback(false,{rows: results});
}
// check null for results here
});
connection.on('error', function(err) {
callback(true);
return;
});
});
};
and in my main class
var db = require('./database');
var user_id = 5
var query = "SELECT * FROM contacts WHERE user_id = ?", user_id;
db.executeQuery(query, function(r,contact_details) {
console.log("success");
console.log(contact_details);
});
It doesn't work. It doesn't even go inside the function or prints success string. But If I do query this
var query = "SELECT * FROM contacts";
This will work. But I want to send a conditional query and because of conditional query, it doesn't work. Don't know how to send a conditional query, for example, this query
var query = "SELECT * FROM contacts WHERE user_id = ?", user_id;
or
"SELECT count(*) as count FROM user_info WHERE user_id = ? AND phone_no_1 = ? OR phone_no_2 = ? OR phone_no_3 = ?",[user_id,formatted_sms_no,formatted_sms_no,formatted_sms_no],
These kind of queries. Any help would be appreciated.
Thank you
As far as I see in module mysql you have the feature called preparing queries.
So basically you should pass query and parameters for executing, f.e. your function definition will look like this function(query, parameters, callback), and than use mysql.format(query, parameters) before executing the query.

node.js synchronously mysql query

I am working in node.js with mySql database.
i'm fetching lat-long routes from googleMaps sanpToRoad Api and insert that data into my table but it's doesn't inserted in flow (sequence)
var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : '',
database : 'myTestDb'
});
var googleAPILink = 'https://roads.googleapis.com/v1/snapToRoads?path='+lastLat+','+lastLong+'|'+currentLat+','+currentLong+'&interpolate=true&key=GOOGLE_MAP_KEY';
console.log(googleAPILink);
var roadResponse = request(googleAPILink, function (error, response, body) {
if (!error && response.statusCode == 200) {
responseData = JSON.parse(body);
for(i = 0; i < responseData.snappedPoints.length; i++) {
var locationArrayObject = responseData.snappedPoints[i];
var locationArrayObjectInsider = (locationArrayObject.location);
var roadLat = locationArrayObjectInsider.latitude;
var roadLong = locationArrayObjectInsider.longitude
var rideStatus = rows2[0].status;
var rideStartedAns = 'n';
if(rideStatus == 's')
{
rideStartedAns = 'y'
}
var post = {
tripid: rideId,
latitude: roadLat,
road_longitude: roadLong,
rideStarted: rideStartedAns,
routeRideCounter: routeCounter,
status: 'y'
};
pool.getConnection(function(err, connectDB4) {
var qry = connectDB4.query('INSERT INTO tbl_rout SET ?', post, function(err5, result5) {
console.log(qry.sql);
connectDB4.release();
});
});
}
}
});
So, here if google Maps API return me in lat-long routes sequence like
1)
lat : 12.3456789,
long : 12.3456789
2)
lat : 23.1456789,
long : 23.1456789
3)
lat : 34.1256789,
long : 34.1256789
then it will may be first insert record 3) then may be insert record 1) then may be insert record 2).
so it will conflict my code and i can't get proper flow of map road path.
please help me.
Issue is your for loop flush all the requests together. Using this technique you cant get control the query execution flow.
There are two ways to achieve this
Dont call insert query in a loop. prepare a query for example
INSERT INTO tableName(field1, field2, field3) VALUES(val1,val2,val3), (val1,val2,val3),....
create query like this and execute it once this will do it in one db call instead of many
Second way is to use async module
async.eachSeries will execute you query one by one instead of flushing and this will enter data in sequence. check example below.
do npm install async --save
var async = require('async');
async.eachSeries(responseData.snappedPoints , function(snappedPoint , cb){
var locationArrayObject = snappedPoint;
var locationArrayObjectInsider = (locationArrayObject.location);
var roadLat = locationArrayObjectInsider.latitude;
var roadLong = locationArrayObjectInsider.longitude
var rideStatus = rows2[0].status;
var rideStartedAns = 'n';
if(rideStatus == 's')
{
rideStartedAns = 'y'
}
var post = {
tripid: rideId,
latitude: roadLat,
road_longitude: roadLong,
rideStarted: rideStartedAns,
routeRideCounter: routeCounter,
status: 'y'
};
pool.getConnection(function(err, connectDB4) {
var qry = connectDB4.query('INSERT INTO tbl_rout SET ?', post, function(err5, result5) {
console.log(qry.sql);
connectDB4.release();
cb();
});
});
}, function(){
console.log('execuation completed);
});

How to make subsequent mongo call after successful call

I have nodejs-mongo setup with db configured as follows (only one entry shown here)
{
"filename":"type1.json","secs":72.4060092977,"platform":"mac","version":"1.3.0", "inputfile":"temp.mov"
},
Here are the mongo commands I am trying to replicate
db.perfR.distinct("platform") * (output: ["mac", "win"] ) *
db.perfR.distinct("version",{"platform":"win"}) * (output: ["1.3.0", "1.3.2"] ) *
db.perfR.find({"version":1.3.2,"platform":"win"},{"filename":1,"secs":1,"_id":0}) * (output: ["filename":"type1.json","secs":72.4060092977] ) *
So what I am trying to do is
for every platform
for every version
get filename
get secs
Here is the code I have written thus far
function createPlatformDataSets(callback){
var dbHost = "mongodb://mongo:27017/perfSample";
var mongodb = require('mongodb')
var platformDataSets = []
var platformq = "platform"
//get Instance of Mongoclient
var MongoClient = mongodb.MongoClient;
//Connecting to the Mongodb instance.
//Make sure your mongodb daemon mongod is running on port 27017 on localhost
MongoClient.connect(dbHost, function(err, db){
if ( err ) throw err;
//use the distinct() to retrive distinct platforms
db.collection("perfR").distinct(platformq,function(err, platResultSet){
if ( err ) throw err;
var maxPlatCnt = platResultSet.length // 1
if (maxPlatCnt == 0){
console.log("Bad PlatfQ Query")
callback(true)
}
var versionedPlatDataSet = 0
for (p=0; p < platResultSet.length; p++){
(function(index){
var platform = platResultSet[index]
var options = createOptions(platform);
//Get Versions
var versionq = "\"version\",{\"platform\":" + platform + "}"
console.log("Versionq::"+versionq)
var dataSets = [];
//var versions = ["1.3.0", "1.3.2"]; // (select disctinct(version) from cpu where platform = plat)
// Use distinct() to find distinct Versions
db.collection("perfR").distinct(versionq,function(err, verResultSet){
if ( err ) throw err;
var maxVerCnt = verResultSet.length // 2
if (maxVerCnt == 0){
db.close()
console.log("Bad Versionq Query")
callback(true)
}
var dataSetResponseCnt = 0
for ( v=0; v < verResultSet.length; v++){
(function(idx){
var dataq = "{platform:" + platform + ",version:" + version + "},{filename:1,secs:1,_id:0}"
// Use find() to find filename and secs for given version and platform
db.collection("perfR").find(dataq,function(err, dataResultSet){
if ( err ) throw err;
if (dataResultSet.length == 0){
console.log("Bad dataq Query")
callback(true)
}
//do something with filename and secs
dataSetResponseCnt++
if (maxVerCnt == dataSetResponseCnt){
var platformData = {"options":options, "labels":labels, "datasets":dataSets, "platform":platform}
platformDataSets.push(platformData)
if (versionedPlatDataSet == maxPlatCnt){
db.close()
callback(null,platformDataSets)
}
}
})
})(v)
}
versionedPlatDataSet++
})(p)
}
}
}
At "1" I am able to retrive distinct platforms
But at "2" I get verResultSet.length to be zero.
Can someone point to me what is wrong?
(PS: This is my first serious async problem with javascript so bear with my code. All suggestions are welcome :) )
you can use Promises. so for example your code is going to be something like this:
return loadPlatforms().then(function (res){
res.map(function(platform){
loadVersion(platform).then(...)
}
})
Your use of .distinct() isn't correct. You are passing a JSON-like string when the API actually takes two separate arguments (not including the callback). So the real code should in fact just be more or less what you originally showed:
var query = { platform: 'win' };
db.collection('perfR').distinct('version', query, function(err, verResultSet) {
// ...
});

How to add JS object into Sqlite database

I am having trouble trying to add a JS Object into an sqlite database. I am using cordova, creating an app for android, windows and iOS.
I have this code for my insert and retrieval...
var data = localStorage.getItem('folderData');
console.log(data);
var username = localStorage.getItem("username");
var session = localStorage.getItem("session_ID");
tx.executeSql('CREATE TABLE IF NOT EXISTS folderData (id integer primary key autoincrement, username, sessionID, folderData text)');
tx.executeSql('SELECT * FROM folderData WHERE username = "'+username+'"', [], function(tx, result) {
if(result.rows.length > 0){
tx.executeSql('UPDATE folderData SET folderData = "'+data+'", sessionID = "'+session+'" WHERE username = "'+username+'"');
alert('An update has occured folderData');
} else {
tx.executeSql('INSERT INTO folderData (username, sessionID, folderData) VALUES ("'+username+'", "'+session+'", "'+data+'")');
alert('An insert has occured folderData');
}
});
tx.executeSql('SELECT folderData FROM folderData WHERE username = "'+username+'" AND sessionID = "'+session+'" ORDER BY id desc LIMIT 1', [], function(tx, result) {
querySuccessFolderData(tx, result);
});
The data variable is my object. When I console.log(data) before insertion i get the following
This my querySuccessFolderData function
function querySuccessFolderData(tx, results) {
var len = results.rows.length;
//alert("folderData table: " + len + " rows found.");
var newFolderData = jsonParse(results.rows.item(0).folderData);
for(i=0;i<len;i++)
{
var newFolderData = results.rows.item(i).folderData;
}
console.log(newFolderData);
}
console.log(newFolderData); now shows up as [Object Object]
What am I doing wrong? Do i need to convert the object again after I select it from the database? This is becoming a nightmare for me now, i've been looking at it for way too long. Any help would be much appreciated.
Managed to fix my issue.
Set my localStorage data.
localStorage.setItem("folderData", JSON.stringify(data['root']));
Used getItem to retrieve it in another function and encoded it for the database insert
var data = localStorage.getItem('folderData');
data = encodeURI(data);
Then used decodedURI and jsonParse to turn it back into an object
var newFolderData = results.rows.item(0).folderData;
newFolderData = decodeURI(newFolderData);
newFolderData = jsonParse(newFolderData);
Which gave me the correct data saved.

Categories