Using value set inside mysql query from outside the query - javascript

I'm using the mysql module and am doing multiple queries into my Mysql database. I'm getting an error in my NodeJS code where the variable "updateQuery" is undefined, even though I set it inside the first query. I thought that since this is synchronous (one query getting executed after the previous finishes) that the variable would be set. I do not want to nest the 2nd query inside the 1st query because I want this to be synchronous.
Is there any way to access the variables that are set inside the first query from outside that query??
Here's the code, given that I'm connected to the database already:
var result;
var updateQuery;
for (var i = 0; i < 5 ; i++) {
connect.query("SELECT * FROM table1 WHERE id = " + i, function(err, result) {
result = result[0];
updateQuery = "UPDATE table2 SET column1 = " + result;
});
connect.query(updateQuery, function(err, result) {
console.log(result);
});
}

Related

Fetch a field from a Multiple MySQL Query in NodeJS?

I'm using NodeJS and need to fetch an audioid field from my first MySQL query, assign it to a variable and use that variable in my next MySQL query. So I've tried to use;
var newaudioid = results[0].audioid;
But the result is coming back as "undefined".
Here's the code;
connection.query(sql, [1, 2], function(err, results, fields){
if (!err) {
res.send(JSON.stringify(results[0]) + JSON.stringify(results[1]));
console.log(results[0]);
console.log(results[1]);
var newaudioid = results[0].audioid;
console.log('newaudioid = ' + newaudioid);
} else {
console.log('Error while performing query.');
console.log(err);
}
});
So console.log('newaudioid = ' + newaudioid); gives me back newaudioid = undefined
How can I fetch that audioid field from my first query?
Following up on your comment
SO I stringified IE: console.log('results0 = ' +
JSON.stringify(results[0])); and got results0 =
[{"audioid":144},{"audioid":147}]
Inside results[0] you have 2 objects that themselves have another object inside, and they both have the same property name. The problem is that javascript does not know which one you are referring to when you are saying results[0].audioid
What you can do is use [0] again to get the first one again, so that would be: results[0][0]

When retrieving data from sql, i want to use the where condition as a variable

I am writing code in conjunction with sql on node js.
I want to load the data according to the condition, and I want to dynamically get the condition depending on the variable.
Here is the current code:
db.all ("select CollectionID, CollectionName from Collection where
CollectionID = abc", function () {
How do I want to receive data according to the variable abc ?
abc's value is number .
var abc = 1;
var query = 'select CollectionID, CollectionName from Collection where CollectionID = ?'
db.all (query, [abc], function (err, rows) {
if (err) throw err;
console.log(rows);
});

Passing an array to a function and pushing values to it using AngularJS

I am trying to populate Arrays dynamically from local storage SQLite Database Tables when a controller is loaded.
I have several Arrays defined as follows (small sample shown):
$scope.myArray1 = [];
$scope.myArray2 = [];
I then create an array with the table name/array name associateion e.g. my_table_1 should be queried and then be written to $scope.myArray1. This looks as below (small sample shown):
$scope.tableArrayAssociation = [{
tablename: "my_table_1",
arrayname: "myArray1"
}, {
tablename: "my_table_1",
arrayname: "myArray2"
}];
To do this I have a function that calls a SQLite local storage database table and reads values from it.For my function I pass the table name to query and array to write the data to as function parameters.
I can query the required table no problem from the passed parameter, but when I try and insert into the array I get an error. Below is said function.
onDeviceReady
function onDeviceReady()
{
queryLocalStorageTablesAndBuildArrays($scope.tableArrayAssociation);
}
Loop through each item, query the table and push to array.
function queryLocalStorageTablesAndBuildArrays(tableArrayAssociation) {
for (var i = 0; i < $scope.tableArrayAssociation.length; i++) {
queryTable($scope.tableArrayAssociation[i].tablename, $scope.tableArrayAssociation[i].arrayname);
}
function queryTable(tableName, arrayName) {
var sql = 'SELECT * FROM ' + tableName + ''; // OK
db.transaction(function (tx) {
tx.executeSql(sql, [],
(function (arrayName) {
return function (tx, results) {
querySuccess(tx, results, arrayName);
};
})(arrayName), errorCB); // OK
});
}
function querySuccess(tx, results, arrayName) {
var len = results.rows.length; // OK
for (var i = 0; i < len; i++) {
$scope[arrayName].push(results.rows.item(i)); // Not working here
arrayName.push(results.rows.item(i)); // Also tried this, but arrayName.push is not a function error thrown
}
}
arrayName.push(...) not working because I am just trying to push to a name (String) and not an actual Array. Showing a log for $scope[arrayName] shows it is an object but that the push didnt work - value = undefined.
Can anyone please suggest a solution to this? How do I assign the queried tables values to its corresponding array to populate values in my view?

NodeJS MSSQL WHERE IN Prepared SQL Statement

I am use nodejs npm package sql
I currently have an array of product skus like so..
var skus = ['product1', 'product2', 'product3'];
My sql store in a file as follows...
SELECT *
FROM stock AS s
WHERE s.sku IN (#skus)
Then I also have my prepared statement code as follows..
var connection = new sql.Connection(config, function(err) {
var ps = new sql.PreparedStatement(connection);
//Add params
if(params != undefined){
for(var key in params){
ps.input(key, sql.VarChar(200));
}
}
ps.prepare(sqlstatement, function(err) {
ps.execute(params, function(err, data) {
callback(null, data);
ps.unprepare(function(err) {
});
});
});
});
}
skus is contained correctly within the params object as the statement works fine when I am using it for simple WHERE X = #YI am just struggling with how I need pass the array of skus to allow them to work in the prepared statement.
I am amend the string using split and join to comma seperate them etc etc but I can't get these methods to work.
I assumed that I would need the param string to look like the following 'product1','product2','product3'.
would be also useful if someone could shed some light on how to debug the completed prepared statement so I can see what is actually being queried to SQL (with params inplace)
Many thanks in advance!
It appears that the sql object (i.e. the mssql module) has no attribute to handle arrays of anything. Moreover, specifying a scalar type in the call to ps.input similarly does not work.
The next best thing is to build keys for your array of parameters into your sql statement itself:
var connection = new sql.Connection(config, function(err) {
var ps = new sql.PreparedStatement(connection);
// Construct an object of parameters, using arbitrary keys
var paramsObj = params.reduce((obj, val, idx) => {
obj[`id${idx}`] = val;
ps.input(`id${idx}`, sql.VarChar(200));
return obj;
}, {});
// Manually insert the params' arbitrary keys into the statement
var stmt = 'select * from table where id in (' + Object.keys(paramsObj).map((o) => {return '#'+o}).join(',') + ')';
ps.prepare(stmt, function(err) {
ps.execute(paramsObj, function(err, data) {
callback(null, data);
ps.unprepare(function(err) {
});
});
});
});
}

sqlite3 and node-js returns undefined

I'm trying to pass value from sqlite3 function with Node.js but I'm getting always undefined.
Here is my code:
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./rolety.db');
var row;
db.get("SELECT open_hour, open_minut FROM autorun_open", function(err, row) {
console.log(row.open_hour);
console.log(row.open_minut);
row = row.open_hour;
});
console.log("R:" + row);
As far, as I can see, its run asynchronously, cause I obtain something like that:
Row: undefined
6
45
Last line of my code is running before sql result. What should I do, to obtain correct value from sql?
You need to add a callback function like this:
db.get("SELECT open_hour, open_minut FROM autorun_open", function(err, row) {
console.log(row.open_hour);
console.log(row.open_minut);
row = row.open_hour;
callback(row);
});
function callback(row) {
console.log("R:" + row);
}
The trick is, that the callback function gets called after the get is successful or not. In the next step you should think about error handling if the get fails.

Categories