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.
Related
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.
I am developing a web application using Angular js and Sails. Now I struck with an issue.In my application there is a menu, which displays different count values from database.Plz see my back
getAllCountMyProfile: function(req,res){
UsertokenService.checkToken(req.get('user-token'), function (err, tokenCheck) {
var userId = tokenCheck.tokenDetails.userId;
var query = "select (select count(*) FROM review WHERE userId="+ userId +" AND approvalStatus = 'approved') AS reviewReceived ,"+
" (select count(*) FROM review WHERE reviewerId="+ userId +" ) AS reviewPenned, "+
"(select count(*) FROM photos WHERE userId="+ userId +" AND accessType='private' AND status='active') AS privatePhotoCount, "+
"(select count(*) FROM photos WHERE userId="+ userId +" AND accessType='public' AND status='active') AS publicPhotoCount";
Review.query(query, function (err, photoReviewCount) {
if(err){
console.log("Error"+ err);
}
else{
return res.json(200, {status:4, message:'success',data1:photoReviewCount});
}
});
UserService.checkVideoLimit(userId, function (err, videoCount)
{
var noVideos=videoCount.data;
console.log("Video count "+noVideos);
return res.json(200, {status: 1, data2: videoCount});
});
var query="SELECT sum(rating) AS totalRating,COUNT(*) AS totalCount FROM review where userId=" +userId+ "";
Review.query(query, function (err, avgRating) {
if(err){
console.log("Error"+ err);
}
else{
var rating=JSON.stringify(result);
var totalRating=result[0].totalRating;
var count=result[0].totalCount;
var avgRatingValue=(totalRating/count).toFixed(2);
console.log(totalRating,count);
console.log("avgRating"+rating);
return res.json(200, {status:4, message:'success',data3:avgRating});
}
});
});`
}
If i execute each return response i got the result. If i Execute the above query , i got error message on console as
"Can't set headers after they are sent."
I need the result data1,data2, data3. what is the solution to obtain this?
You cannot set the response more than one time. Either you can use res.write and edit the response for queries and then send it with res.end() or you can change your code to send the response only once. Something like this:
res.status(200).json({
"data":{
"data1":photoReviewCount,
"data2":videoCount,
"data3":avgRating
}
})
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);
Hi i am creating an empty array then populating it with data from a mongo query using a forEach Loop.
i have been attempting this now for 4 days and nothing i seem to do is working i know im close but being a newbie to javascript and MEAN stack i just cant figure it out.
i have attached the code with comments on everything i am trying to do.
please any help would be awesome..
var mongoose = require('mongoose'),
User = require('../../models/UserModel'),
async = require('async');
module.exports.getfollowing = function(req, res){
//grab the Users ID from the body
var thefollower = req.body.follower;
//create empty array that i want to populate with the followee's ID and Avatar url
var obj = [];
//query mongo for the user
User.findOne({ _id: thefollower }, function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
//grab the following element of the users mongo schema -- should return all the followee's ID's -- tested works
var following = user.following;
//iritate throught all the followee's
async.forEach(following, function(item, callback) {
//current followee
var user = item;
//query mongo for the followee
User.findOne({_id: user}, function(err, followee, callback){
//get followee's ID and Avatar url
var id = followee._id;
var avatar = followee.avatar;
//add the followee's ID and Avatar url to the obj array
obj.push({
id: id,
avatar: avatar
});
});
//see if this worked - returns empty
console.log(obj);
callback();
}, function(err) {
//see if this worked - returns empty
console.log(obj);
//respond to the client - returns empty
res.json(obj);
});
}
});
};
You need to move your callback(); that is at the end of your async.forEach() callback to inside the User.findOne({_id: user}, ...) callback (right after you call obj.push()) because that is when you are actually done with item. With your current code you are telling the async module immediately that you are done with item, before your mongo query has a chance to complete.
mscdex
Was spot on his answer solved my issue for future help to others here is the code
var mongoose = require('mongoose'),
User = require('../../models/UserModel'),
async = require('async');
module.exports.getfollowing = function(req, res){
//grab the Users ID from the body
var thefollower = req.body.follower;
//create empty array that i want to populate with the followee's ID and Avatar url
var obj = [];
//query mongo for the user
User.findOne({ _id: thefollower }, function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
//grab the following element of the users mongo schema -- should return all the followee's ID's -- tested works
var following = user.following;
//iritate throught all the followee's
async.forEach(following, function(item, callback) {
//current followee
var user = item;
//query mongo for the followee
User.findOne({_id: user}, function(err, followee){
//get followee's ID and Avatar url
var id = followee._id;
var avatar = followee.avatar;
//add the followee's ID and Avatar url to the obj array
obj.push({
id: id,
avatar: avatar
});
//see if this worked - returns empty
console.log(obj);
callback();
});
}, function(err) {
//see if this worked - returns empty
console.log(obj);
//respond to the client - returns empty
res.json(obj);
});
}
});
};
I am trying to select everything from contracts db and compare the first name of HTML5 textbox with the db entry to alert for duplicates. My first target is to save the result of the query into sql2 variable. ( I cannot do that , please help! ).
db = window.openDatabase("contactDB", "1.0", "Contact Database", 1000000); //name,version,display name, size
addButton.addEventListener(
"click",
function(){
db.transaction(
//function sql statements
function (tx){
ensureTableExists(tx);
var firstName = firstNameBox.value;
var lastName = lastNameBox.value;
var sql = 'INSERT INTO Contacts (firstName, lastName) VALUES ("'+firstName+'","'+lastName+'")';
tx.executeSql(sql);
// Attempting to check for duplicates
var sql2 = 'SELECT * FROM Contacts', WHERE firstName = "'+firstname+'";
tx.executeSql(sql2);
alert(sql2);
},
//error callback
function (err) { alert("error callback "+err.code); },
//success callback
function (err) { //alert("success callback "+err.code);
loadFromDB();
}) // db.trasaction
} // click handler
);
Lookin at this line:
var sql2 = 'SELECT * FROM Contacts', WHERE firstName = "'+firstname+'";
JS variable "firstname" is mistyped (No capital N on Name). This will turn your query into:
'SELECT * FROM Contacts WHERE firstName = "undefined"'
Also, why is there ', before WHERE? I am surprised you did not get an error.
Try rewriting your query like so:
var sql2 = 'SELECT * FROM Contacts WHERE firstName = "'+firstName+'"';