I have https://www.npmjs.org/package/mysql module.
They show examples how to use it when multiple rows are expected, but I couldn't find one example showing how to fetch a single result into a variable.
SELECT name FROM users WHERE id=1 LIMIT 1
how do I fetch this into sqlValues variable ?
In the callback function of the .query method, the second parameter contains an array containing the rows returned from your query. No matter how many are returned, these can be indexed just as an array.
Thus, in the callback function to get the single expected result, you can use rows[0].
In your specific instance, to assign the returned name field to the sqlValues variable, you can use a simple assignment: sqlValues = rows[0].name
You can see the code below which connects to sql and fetches data.
var mysql = require('mysql');
var connection = mysql.createConnection(
{
host : 'localhost',
user : 'your-username',
password : 'your-password',
database : 'wordpress',
}
);
connection.connect();
var queryString = 'SELECT name FROM users WHERE id=1 LIMIT 1';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;
for (var i in rows) {
console.log('Post Titles: ', rows[i].yourcolumnname);
}
});
connection.end();
you can implement this code like this … (more simple)
var queryString = 'SELECT name FROM users WHERE id=1 LIMIT 1';
connection.query(queryString, function(err, rows) {
if (err) throw err
res.send(rows)
console.log(rows)//this
});
connection.end();
Related
I am using SOLR as my database and I have to delete all the records from the database where (UUID: 'a7d37405-fd5b-44de-b4bc-e748e9353f5d' and name:'Murtaza'). I can delete it by using just 1 field but it does not allow me to delete using 2 where clauses. Is there any way to do this?
I am using this code:
var objQuery = {UUID:'a7d37405-fd5b-44de-b4bc-e748e9353f5d'}
client.delete(objQuery, function(err, result) {
if (err) {
console.log(err);
return;
}
client.softCommit();
callback(result.responseHeader);
});
The inbuilt delete function only allows the 1 field+value as an argument, but you could use the deleteByQuery option:
http://lbdremy.github.io/solr-node-client/code/deleteByQuery.js.html
And make the query a conditional search for both fields:
var query = "UUID:'abcd-1234' AND name:Murtaza";
I found the solution finally! We have to use deleteByQuery function. The function code is:
var client =solr.createClient(options);
var query = 'UUID:814caeda-5ef1-4ecf-8260-222060d9907c AND toolId:mytoolID';
client.deleteByQuery(query,function(err,obj){
if(err){
console.log(err);
}else{
client.softCommit();
callback(obj.responseHeader);;
}
});
I am very new to PostgreSQL please bear with me.
I need to read records from the table using select query with where condition.
Eg: select * from switch where switchId=10;
QueryFactory.js
let queryMap = {
“getSwitchInfo”: ‘select * from switch where switchId=?’
}
module.exports=queryMap;
Controller.js
let client = require(rootdir+’dao/postgresSQL’);
let queryFactory = require(rootdir+’/dao/QueryFactory’);
let query = queryFactory.getQuery(“getSwitchInfo”);
let switchId = req.query.switchId;
client.query(query, function(err, res){
if(err){
}
});
Please see:- this switchId value 10 I get from client and using query parameter I am getting it in my node backend layer.
Kindly suggest how can I pass switchId to the query as a parameterized value.
I found solution myself for this issue. Added params to an array and passed this array as a second param to client.query method and in the query where condition I added $1. It is working fine now
QueryFactory.js
let queryMap = {
“getSwitchInfo”: ‘select * from switch where switchId=$1’
}
module.exports=queryMap;
Controller.js
let params = [req.query.switchId];
client.query(query, params, function(err, res){
if(err){
}
});
In a post function, I am trying to retrieve the nth activity of a user (since I have a dropdown that return the index number of the activity). When I run the query
collection.find({'local.email':req.user.local.email},
{'local.activities':{$slice : [currActivity,1]}});
I receive the correct activity object in Robo3T.
But, when I call the same query in Node inside a post function, it returns an undefined.
app.post('/addlog',function(req,res){
var currActivity = req.body.curAct;
var score = req.body.score;
var comment = req.body.reason;
mongoose.connect('mongodb://****:****#ds044907.mlab.com:44907/intraspect',function (err, database) {
if (err)
throw err
else
{
db = database;
var collection = db.collection('users');
var retrievedAct = collection.find({'local.email':req.user.local.email},
{'local.activities':{$slice : [currActivity,1]}}).toArray().then(console.log(retrievedAct));
if (retrievedAct.length > 0) { printjson (retrievedAct[0]); }
console.log(currActivity);
console.log(retrievedAct[0]);
// console.log(req.body.newAct);
collection.update({'local.activities.name':retrievedAct[0]},
{$push: {'local.activities.log' : {
comments: comment,
score: score,
log_time: Date.now()
}}})
.then(function(){
res.redirect('/homepage');
})
.catch(function() {
console.log('Error');
});
}
});
});
I checked that the currActivity variable does infact contain the integer value for the nth activity.
If you want the result of collection.find().toArray(), as specified in the docs, you have two options:
Passing a callback to .toArray() like you did with mongoose.connect()
Using the Promise that it returns if you don't pass a callback
Now you are doing neither of them.
Also, you are mixing callback style and Promises in your code. I recommend you unificate your code. If you are using a Node.js version bigger than 8, using async/await could be nice, it makes it simpler.
I've got a problem with javascript/node js functions.
When I send an sql query with function query of "request.service.mssql" object, the result function is called twice...
I don't understand because my sql query is an "update" and the result is empty (I do not have multiple lines of results)
For example, I have a function that send an email with a new password. The email is sent twice... I found a temp solution with an index but it's not very clean.
Can you explain this ?
//construct SQL query
var email = "test#toto.com";
var password = require("crypto").randomBytes(4).toString('hex');
var password_md5 = require("crypto").createHash("md5").update(password).digest("hex");
var sql = "update dbo.mytable SET password='"+password_md5+"' where id=12";
var id = 0; //temp solution
mssql.query(sql,
{
success: function(results) {
//Send email with new pwd
if(id == 0) {
response.send(statusCodes.OK,password_md5);
sendEmail(email,password);
}
id++; //temp solution
},
error: function(err) {
response.send(statusCodes.INTERNAL_SERVER_ERROR,"Error : " + err);
}
});
Thank you :-)
Steve
I get the answer on another forum : I have to prefix my SQL statement with set nocount on; command.
Thank you for your help.
Steve
In node-socketchat system, i am using mysql module.
I wants to take data after checking through 4-5 tables, but cannot make a join statement.
suppose i need to take a friends collection and their details.
Now i am following below method.
var friends = new Array();
var connection = mysql.createConnection(database);
connection.query(sql, function(err, rows, fields) {
if (err) throw err;
for (var key in rows) {
friends.push(rows[key].friendid);
// Here i am expecting to write another sql statement
}
getfriendsdetails(friends)
connection.end();
})
function getfriendsdetails(friendslist){
connection = mysql.createConnection(database);
sql = 'select statment for taking friends details in in statement'
connection.query(sql, function(err, rows, fields) {
//storing each row detail in to an array
});
}
My Question is, can i call the details query inside first for loop ? is it possible ?