node mysql not executing query - javascript

I'm having trouble executing my update query. Right now it's inside the select query witch works fine, the update queries are well formed, since I can copy paste a single update query from the output and it will update accordingly. no errors thrown, stream with update string appear but none are executed.
connection.connect();
connection.query('SELECT text, id from twits2 order by id ASC', function(err, rows) {
rows.forEach(function(row){
var id = row.id;
var r1 = sentiment(row.text);
var score = r1.score;
var comparative = r1.comparative;
var q = 'UPDATE twits2 SET score ="'+score+'", comparative ="'+comparative+'" WHERE id="'+id+'"';
console.log(q);
connection.query(q, function (error, results, fields) {
if (error) throw error;
});
});

Related

Variable undefined nodeJS MySQL query

I have a table with different post categories and I want to get the categories ID from the name. Example name: random => id: 1.
I got the variable like this:
const { name, title, cat, con, user_file } = req.body;
console.log(cat); //returnes the name as it should
This is my query:
var sql = "SELECT id FROM cat WHERE cat_name = ?";
db.query(sql, cat, function(err, result) {
if(!result){
return next();
}
const cat_id = result[0];
});
If I than try to console.log the cat_id I get undefined. I have tried doing this in many different way but it comes out the same every time. If I just run
SELECT id FROM cat WHERE cat_name = random
in thee database manager it works like it should and returnes the ID.
Edit: The purpose is to get the id to insert a foreign key into another table.
Your results is an empty array. This is (assuming you're using the mysql package) because your function call is incorrect.
When passing arguments to your query, as explained here, you need to pass an array of values, not just a single value. For example:
connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
In your case, that means you're looking for cats where the name is the first character of cat (e.g. cat[0]).
It ended up being a problem with variables only being saved in the query level. It console.logged the right number inside the db.query and the wrong one out of the db.query. So the solution for now is to put it inside I guess.
My solution now looks like this:
exports.post = (req, res, next) => {
let { cat } = req.body;
let cat_id = 0;
db.query(
"SELECT id FROM cat WHERE cat_name = ?",
[cat],
async function (err, results) {
if (!err) cat_id = results[0].id;
else console.log(err);
db.query(
"INSERT INTO posts SET ?",
{ cat_id: cat_id },
(error, results) => {
if (error) console.log(error);
else res.status(200).redirect("/post");
}
);
}
);
};

NodeJs + Mysql Multi Query with chain method

Hi friends I have to ask the mysql query repeatedly in my application with Node js. I will shape the second interrogation according to the result of the first interrogation. The following code example does not work. Can you help me? You can support the functioning of the queries do not hang.
let sql = "SELECT COUNT(*) AS miktar FROM orders";
connection.query(sql, function(err, result) {
if (err) throw err;
let sqlAnother =
"SELECT COUNT(*) AS miktar FROM orders WHERE result=" +
result[0].miktar +
"";
connection.query(sqlAnother, function(err, result) {
if (err) throw err;
callback(result);
});
});
connection.end();
You can do this in one call with a subquery:
SELECT COUNT(*) AS miktar FROM orders WHERE result = (SELECT COUNT(*) FROM orders)
If this returns a result in the MySQL CLI, then your code must provide this result to callback. Otherwise it's just that no row in orders happens to have a field result that contains the exact amount of rows in the table.

How to SELECT multiple records from MySQL DB in an Node.js based application & node-mysql driver?

I am running the below query in mysql db and i want to store the results in an array ? How can I do that in node.js ?
SELECT ProductName FROM products;
The last SELECT statement you have described is almost correct except that it uses structure for the INSERT statement.
Here is 2 correct ways to create and execute SELECT statements, the safe way, to avoid MySQL injections and to secure your database from possible attacks.
1. Multiple Records
/**
* Example of Selecting multiple rows form one MySQL table
*/
var query = connection.query('SELECT ProductName FROM products',
[product_id], function(err, results) {
if (error) throw error; output error(s)
// results[0]['ProductName'];
// results[1]['ProductName'];
// ...
});
Using a prepared Statement targeting for specific rows:
/**
* Example of Selecting one record using MySQL Table ID
*/
var category_id = 5;
var query = connection.query('SELECT ProductName FROM products WHERE CategoryId=?',
[category_id], function(err, results) {
if (error) throw error; output error(s)
// results[0]['ProductName'];
// results[1]['ProductName'];
// ...
});
Using mysql.escapeId() method
var category_id = x;
var sql = 'SELECT productName FROM products WHERE category_id = ' + connection.escape(category_id);
connection.query(sql, function (error, results, fields) {
if (error) throw error; output error(s)
// results[0]['ProductName'];
// results[1]['ProductName'];
// ...
});

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);
});

How to obtain the value of the result in a `node-mysql` query

I am weighting a node.js application, the result I get from my mysql query is,
[ RowDataPacket { name: 'ubuntu' } ]
(Ubuntu is the only thing in the row)
What I would like to do is shorten my variable, "results" so that it equals ubuntu for example, or just every thing between the '', I am new to JS. I am using the standard way of querying the sql database,
It is being done as so:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root', //just using root for my personal testing.
password : 'root',
database : 'Sonic'
});
connection.connect();
var connect = connection.query( 'SELECT name FROM Sonic_url',
function(err, fields, results, rows) {
// if (results === input) {
var sqldata = results.substring(1, 4);
console.log(results);
if (err) throw err;
// console.log('I belive we have found what you are after, is: ' + input + ' ' + 'what you are after?');
//}
});
I would like to be able to do a basic IF with the variable input and a variable from the mysql query, so I can print to screen if the result was found or not.
The correct signature for the mysql query is:
connection.query(query, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
What you want is to log the value of name. If your query produces one result, you can access this value from the first item in the rows array:
connection.query('SELECT name FROM Sonic_url', function(err, rows, fields) {
console.log(rows[0].name);
});

Categories