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 ?
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 met an annoyance when trying to use simple function to query data for my web app. The idea is to use one function to list the contents of one table; the other function to use the user-selected record_id in this table to query the detailed contents data in another table.
When running, the app ran the two functions without any error while no data got. Checked the console and found the second function query results is null (I console.log the input for the second function, found they got and using the correct query keys). Since I am sure database has the data for query.
I tried:
use psql command line to query data using the same query keys, I have the results without problem;
I run a node command line, and try to run the two functions by providing the query keys, it also gave me the correct results.
So the functions should work. Now my question is why put them in the app and let them run by themselves, they did not get the query results?
I am using pg = require("pg"); and const pool = new pg.Pool(config) for database connection;
Your sharing of your experience will be very appreciated.
(UPDATE)The functions are like below:
function listItemDB(callback){
pool.connect(function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
//use the client for executing the query
client.query(`SELECT * FROM basicdb.items`,
function(err, result) {
//call `done(err)` to release the client back to the pool (or destroy it if there is an error)
done(err);
if(err) {
return console.error('error running query', err);
}
// console.log(result.rows);
callback(result.rows);
});
});
}
The above function is only trying to get "item1" and "dataset1" for future use and pass them to below function args. It does its job perfectly.
function getFileName(itemName,datasetName, callback) {
let fileName;
console.log(itemName,datasetName);
pool.connect(function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
client.query("SELECT * "+
"FROM basicdb.dataset "+
"INNER JOIN basicdb.items "+
"ON basicdb.dataset.item_id = basicdb.items.item_id "+
"WHERE (basicdb.items.item_name = ($1)) "+
"AND (basicdb.dataset.datasetname = ($2))",[itemName,datasetName],
function (err, result){
done();
if(err) {
return console.error('error running query', err);
}
let records = result.rows;
fileName = records[records.length-1].filename;
callback(fileName);
});
});
}
This above function is trying to get the filename so the main app can use it. The code to call the above function in my main app.js is like below:
db.getFileName("item1","dataset1",function(fileName) {
//do something with the fileName....}
("db" is the module name which include the functions.)
I finally found the problem, which is a low-level mistake and has nothing to do with the database and the queries.
The item names got from the dropdown list in the app, which was feed to the function args, has one " "(space) attached to the end of the name(i dont know why?), which always "!=" the record in the database:-(, so always no query result in the app. But for the function test, I hardcode the item name which is correct "==" the record in the database. Since it is " ", even when I console.log(itemName), I did not find the space at the end.
It turns out to be 'A mistake of space'.
Hi Can anyone give an example of how use insert statement in nodejs. I am able to use select query. But for insert query i am getting the result as []. no error can be seen but the values are not added to the original table. I am using db2, ibm_db,express,nodejs and angularjs.
I wrote a blog entry on using DB2 and node.js on Bluemix a while ago. It includes code for an INSERT statement.
As part of the insert
first prepare the statement,
then bind the values to be inserted and
finally execute the statement.
Here is the relevant code snippet, the full context is in the blog:
exports.insertIP = function(ibmdb,connString,ipinfo) {
console.log("insertIP called",ipinfo);
ibmdb.open(connString, function(err, conn) {
if (err ) {
res.send("error occurred " + err.message);
}
else {
// prepare the SQL statement
conn.prepare("INSERT INTO IP.VISITORS(vtime,ip,country_code,country,region_code,region,city,zip,latitude,longitude,metro,area) VALUES (current timestamp,?,?,?,?,?,?,?,?,?,?,?)", function(err, stmt) {
if (err) {
//could not prepare for some reason
console.log(err);
return conn.closeSync();
}
//Bind and Execute the statment asynchronously
stmt.execute([ipinfo["ip"],ipinfo["country_code"],ipinfo["country_name"],ipinfo["region_code"],ipinfo["region_name"],ipinfo["city"],ipinfo["zipcode"], ipinfo["latitude"], ipinfo["longitude"],ipinfo["metro_code"],ipinfo["area_code"]], function (err, result) {
console.log(err);
// Close the connection to the database
conn.close(function(){
console.log("Connection Closed");
});
});
});
}
})};
I would suggest and recommend (as one of the members of node-ibm_db) to follow the node-ibm_db github repository (https://github.com/ibmdb/node-ibm_db) , we have updated the README document as well as the list of APIs to do particular tasks.
For your above query you can use ".prepare(sql, callback)" or ".prepareSync(sql)" API (as per your requirements Async/sync call), below is the attached code snippet and URL link for particular API documentation.
var ibmdb = require("ibm_db"),
cn ="DATABASE=dbname;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=dbuser;PWD=xxx";
ibmdb.open(cn,function(err,conn){
conn.prepare("insert into hits (col1, col2) VALUES (?, ?)",
function (err, stmt) {
if (err) {
//could not prepare for some reason
console.log(err);
return conn.closeSync();
}
//Bind and Execute the statment asynchronously
stmt.execute(['something', 42], function (err, result) {
if( err ) console.log(err);
else result.closeSync();
//Close the connection
conn.close(function(err){});
});
});
});
API documentation(Github URL) : https://github.com/ibmdb/node-ibm_db#-8-preparesql-callback
Try to install jt400 by using the below command
npm install node-jt400 --save
use the below code to insert the data to table name foo.
Follow link https://www.npmjs.com/package/node-jt400 for for details
pool
.insertAndGetId('INSERT INTO foo (bar, baz) VALUES(?,?)',[2,'b'])
.then(id => {
console.log('Inserted new row with id ' + id);
});
i'm using two function function1, function2 consequetivly in node.js.
function1 using to insert the data into the table.
for(var j=0; j < length; j++){
connection.query('INSERT INTO TestTable SET ?', { row_name : name }, function(err, res){
if(err) throw err;
});
}
function2 using to select the count of inserted name, count.
connection.query('select row_name, count(*) as count from TestTable where row_name = ?', name , function (err, rows){
console.log(rows);
});
where my log gives me name : null, count : 0
what i'm doing wrong?
First of all, running mysql queries in a loop is a bad practice. Second,
you miss the basics of the asynchronous flow in javascript. Here is a good article where the the basic concepts of asynchronous programming in JavaScript are explained. connection.query is asynchronous, so if you want your code to work, you should run counting query in the callback of the insert query on last iteration.
But as I already mentioned, it is a bad practice to run them in a loop. I would advice you only to build query string in a loop for multiple inserts, but run it only once in the end (with a counting query in the callback).
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();