node mysql insert and select count not working - node.js

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).

Related

Couchbase basic bucket N1QL query NodeJS script not returning any value

I have a basic NodeJS Couchbase script straight from their documentation. It just inserts a document and immediately N1QL queries the inserted document.
var couchbase = require('couchbase')
var cluster = new couchbase.Cluster('couchbase://localhost/');
cluster.authenticate('admin', 'admini');
var bucket = cluster.openBucket('application');
var N1qlQuery = couchbase.N1qlQuery;
bucket.manager().createPrimaryIndex(function() {
bucket.upsert('user:king_arthur', {
'email': 'kingarthur#couchbase.com', 'interests': ['Holy Grail',
'African Swallows']
},
function (err, result) {
bucket.get('user:king_arthur', function (err, result) {
console.log('Got result: %j', result.value);
bucket.query(
N1qlQuery.fromString('SELECT * FROM application WHERE $1 in
interests LIMIT 1'),
['African Swallows'],
function (err, rows) {
console.log("Got rows: %j", rows);
});
});
});
});
This is returning back
bash-3.2$ node nodejsTest.js Got result:
{"email":"kingarthur#couchbase.com","interests":["Holy
Grail","African Swallows"]}
Got rows: []
I was expecting the inserted document in the "rows" array.
Any idea why this very basic nodeJS starter script is not working?
Key/value read writes are always consistent (that is, if you write a document, then retrieve it by ID, you will always get back what you just wrote). However, updating an index for N1QL queries takes time and can affect performance.
As of version 5.0, you can control your consistency requirements to balance the trade-off between performance and consistency. By default, Couchbase uses the Not_bounded mode. In this mode, queries are executed immediately, without waiting for indexing to catch up. This causes the issue you're seeing. Your query is executing before the index has been updated with the mutation you made.
You can read about this further here: https://developer.couchbase.com/documentation/server/current/indexes/performance-consistency.html

how get resultat mariadb nodejs

This is my code:
var Maria = require('mariasql');
c = new Maria({
host: '127.0.0.1',
user : 'root',
password : 'maria',
db : 'gim'
});
c.query('SELECT * FROM contact WHERE id = ? AND nom = ?', [4, 'dupont'], function(err, rows) {
if (err) {
throw err;
}
else {
function getResult() {
return rows;
}
}
});
c.end();
//get overs file
console.log(getResult());
I want resultant data but getResult() is not defined.
How can I get resultant with node.js?
Well there are several errors on your code.
Most of them related to basic JS programming concepts. So I will suggest you to look for some JS courses or tutorials.
When you define getResult function, you're doing it inside of a function's clousure. Which means that, this function will be only accessible inside that function.
The function where you've declared that getResult function, is actually a callback which is a function that will get executed as soon as some operation completes, normally an I/O intensive operation. Like in your case reading records from the database.
When the last statement gets reached and executed your query did not return, as of per node.js non-blocking I/O, the control of the program executes c.query... and this is where you provide that callback that we mentioned earlier, so it can continue the execution of the rest of statements, and when the c.query... returns with the records, execute the callback with them as result. But by then console.log... would have been executed.
I'm not sure if this is an understandable answer, in part because the concepts that I've tried to explain are really basic to the language that you're using, so one more time I would suggest to start by a tutorial/course. There are some good ones on CodeSchool and so many other sites.

Passing extra parameters for mysql query callback function in node js

I am trying to run a mysql query using node js and in the callback function I want to pass some additional parameters.
for (var i = 0; i < categories.length; i++)
{
connection.query ('select * from products where category=' + categories[i] , function (err, products) {
if (products != undefined && products.length > 0)
{
// want to do some processing based on product data and category name
}
});
}
In the above code, how can I pass category name to the callback function? I know I can do a join in the sql query and that will give me the data in the products but just want to know if there is anyway of passing the data in the callback function.
Just use const. Also, never construct queries by simply concatenating strings with variables.
Example:
for (var i = 0; i < categories.length; i++)
{
const categoryName = categories[i];
connection.query('select * from products where category = ?',
[categoryName],
function (err, products) {
if (err)
throw err;
if (products.length > 0)
{
// use `categoryName`
}
});
}
You may also want to consider using a database connection pool instead of just a single connection (since all queries are queued and only one query can be executing at any given time per connection).

NodeJS, wait.for module and mysql query

Trying to use the wait.for module with a mysql query ( can do it with callbacks but would be nice to be able to do it with 'wait.for' )
I know that the sql connection query is non-standard so I'm not sure how to convert it.
var getUserQuery = "SELECT * FROM x WHERE id= '5'";
connection.query(getUserQuery, function(err, rows, fields){
....
});
How would I go about waiting to get the rows of this before my code proceeds on ?
link to module 'wait.for'
The part I am not understanding is at the bottom of that page - (Notes on usage on non-standard callbacks. e.g.: connection.query from mysql ).
https://github.com/luciotato/waitfor#notes-on-usage-on-non-standard-callbacks-eg-connectionquery-from-mysql
Notes on usage on non-standard callbacks. e.g.: connection.query from mysql
wait.for expects standardized callbacks. A standardized callback always returns (err,data) in that order.
A solution for the sql.query method and other non-standard callbacks is to create a wrapper function standardizing the callback, e.g.:
connection.prototype.q = function(sql, params, stdCallback){
this.query(sql,params, function(err,rows,columns){
return stdCallback(err,{rows:rows,columns:columns});
});
}
usage:
try {
var getUserQuery = "SELECT * FROM x WHERE id= ?";
var result = wait.forMethod(connection, "q", getUserQuery, ['5']);
console.log(result.rows);
console.log(result.columns);
}
catch(err) {
console.log(err);
}

In node can we use multiple mysql statements in one connection query?

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 ?

Resources