I am trying to filter some data by "averageRating".
This is my code for the method:
filterr(request, respond) {
var averageRating = request.params.rating;
var sql = "SELECT * FROM shopreview.shops WHERE averageRating = ?";
db.query(sql, [averageRating], function (error, result) {
if (error) {
throw error;
}
else {
respond.json(result);
}
});
}
My sql statement is working when I test it against my database. However, I keep getting [] as my result. Can someone please help identify what the problem is? Thanks a lot!
the problem is that "?" since the db is unable to parse it.
either add that avarageRating variable like so:
var sql = "SELECT * FROM shopreview.shops WHERE averageRating = ${parseInt(avarageRating)}";
or if you're using couchbase you could parse it like this:
var sql = `SELECT * FROM shopreview.shops WHERE averageRating = $1`;
where $1 is the first variable in the array of variables.
Related
I'm not sure what I'm missing, I thought putting Games in brackets would let me do bulk insert to MySQL. However when I do this it comes back as (OBJECT,OBJECT). If I remove the brackets then I only get one single insert but it works! Any suggestions to do bulk insert?
Short sample of the Array
[{title:xxx,link:https://xxxx,description:xxx.,xxx:xxxxx},{title:xxx,link:https://xxxx,description:xxx.,xxx:xxxxx}]
Javascript
// Writing the Games inside a json file
fs.writeFile("feed.json", JSON.stringify(Games), function(err) {
if (err) throw err;
console.log("Saved!");
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sqlquery = "INSERT INTO gtable (title, link, description, company) VALUES ?";
let queryData = {
sql: sqlquery,
values: [Games]
}
con.query(queryData, function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
I believe your issue may be that you are passing an array of objects while MySQL is expecting an array of arrays.
Your format is basically:
var sqlquery = "INSERT INTO gtable (title, link, description, company) VALUES ?";
var values = [
[{title:xxx,link:https://xxxx,description:xxx.,xxx:xxxxx}
{title:xxx,link:https://xxxx,description:xxx.,xxx:xxxxx}]
];
When it should be:
var sqlquery = "INSERT INTO gtable (title, link, description, company) VALUES ?";
var values = [
[[title1,link1,description1,xxx1],
[title2,link2,description2,xxx2]]
];
You would need to convert each object to an array of just its values. Which you could do with something like this I think:
let sqlValues = Games.map(obj => Object.values(obj));
EDIT: I had the incorrect format for the mapping, fixed now.
I believe #otw has a solid solution (and an awesome explanation of why this is happening), but to offer an alternative solution you could do something like this:
Games.forEach(game => {
con.query('INSERT INTO gtable SET ?', game, insertErr => {
if (insertErr) {
throw new Error("Error inserting game " + game.title + "! " + insertErr);
}
console.log(`Inserted ${game.title}!`);
});
})
I have a table that has a column named CRS_TITLE and I would like to search a list of course titles within that column. Right now my code only works with one argument at a time. I suppose I can write a simple loop, and during each iteration I can just call db.each() again with a new class name. I know this way is inefficient, so I would like to check all the arguments within one pass.
Things I have tried:
1) Adding another '?' in WHERE and other variations.
2) Using the new spread operator from javascript like [...classes] when passing in the arguments.
None of the above works due to syntax error.
Anyways, here is my code below.
let sqlite3 = require('sqlite3').verbose()
// open the database
let db = new sqlite3.Database('./classes.db', (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the classes database.');
});
let sql = `SELECT CRS_CDE course_code,
Column3 start_time,
Column4 end_time
FROM spring_schedule
WHERE CRS_TITLE = ?`;
// I want to do multiple "WHERE = ?" here.
// with multiple arguments
let className1 = 'Spanish I'
// I want to change the line above to this instead.
// let classNames = ['Accounting I', 'English', 'Math'...etc]
db.each(sql, [className1]/*pass an array of items to look up instead of just 1 item.*/, (err, row) => {
if (err) {
throw err;
}
console.log(`${row.course_code} ${row.start_time} - ${row.end_time}`);
// Will use this result to update frontend.
});
// close the database connection
db.close();
EDITED: working code below.
let sql = `SELECT CRS_CDE course_code,
Column3 start_time,
Column4 end_time
FROM spring_schedule
WHERE CRS_TITLE IN `;
let classNames = ['Spanish I', 'Accounting II', 'College Algebra']
let where = '(?' + ',?'.repeat(classNames.length-1) + ')';
sql += where;
db.each(sql, [...classNames], (err, row) => {
if (err) {
throw err;
}
console.log(`${row.course_code} ${row.start_time} - ${row.end_time}`);
// Will use this result to update frontend.
});
db.close();
You may try building a dynamic WHERE IN clause using the exact number of parameters to match your input array:
let sql = `SELECT CRS_CDE course_code, Column3 start_time, Column4 end_time
FROM spring_schedule
WHERE CRS_TITLE IN `;
let classNames = ['Accounting I', 'English', 'Math'];
let where = '(?' + ',?'.repeat(classNames.length-1) + ')';
sql += where;
db.all(sql, [], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row.name);
});
});
db.close();
Hello I have database and queries written in a module and I am calling the module from the main class. What I want is to pass a query in function and get results. This is what I am doing so far
database.js
var pool = mysql.createPool({
host : 'localhost',
user : 'xxxx',
password : 'xxx',
database : 'xxx'
});
exports.executeQuery=function(query,callback){
pool.getConnection(function(err,connection){
if (err) {
console.log("error comes " + err);
callback(true);
return;
}
connection.query(query,function(err,results){
connection.release();
if(!err) {
console.log("no error");
callback(false,{rows: results});
}
// check null for results here
});
connection.on('error', function(err) {
callback(true);
return;
});
});
};
and in my main class
var db = require('./database');
var user_id = 5
var query = "SELECT * FROM contacts WHERE user_id = ?", user_id;
db.executeQuery(query, function(r,contact_details) {
console.log("success");
console.log(contact_details);
});
It doesn't work. It doesn't even go inside the function or prints success string. But If I do query this
var query = "SELECT * FROM contacts";
This will work. But I want to send a conditional query and because of conditional query, it doesn't work. Don't know how to send a conditional query, for example, this query
var query = "SELECT * FROM contacts WHERE user_id = ?", user_id;
or
"SELECT count(*) as count FROM user_info WHERE user_id = ? AND phone_no_1 = ? OR phone_no_2 = ? OR phone_no_3 = ?",[user_id,formatted_sms_no,formatted_sms_no,formatted_sms_no],
These kind of queries. Any help would be appreciated.
Thank you
As far as I see in module mysql you have the feature called preparing queries.
So basically you should pass query and parameters for executing, f.e. your function definition will look like this function(query, parameters, callback), and than use mysql.format(query, parameters) before executing the query.
sql.get(`SELECT * FROM scores ORDER BY points DESC`).then(allScores => {
console.log(allScores);
});
This should give me all of the rows ordered by points, but I'm only getting the first row.
How do I access all of the other rows using javascript?
Use sql.all instead of sql.get refer http://www.sqlitetutorial.net/sqlite-nodejs/query/
Define your db instance as follows:
const sqlite3 = require('sqlite3').verbose();
// open the database
let db = new sqlite3.Database('./db/yourCoolDB');
And then,
let sql = `SELECT * FROM scores ORDER BY points DESC`;
db.all(sql, [], (err, rows) => {
if (err) {
throw err;
}
rows.forEach((row) => {
console.log(row.Id); // You can use row.yourAnotherAttributeName
});
});
I have this mysql query written in node.js mysql and restify to be executed in a HTTP GET.
https://github.com/felixge/node-mysql
var api_get_func = function (app, url_path) {
function respond(req, res, next) {
var id= req.query.id;
var limit = req.query.limit;
var query_str =
"SELECT table.sw_type, " +
"FROM users " +
"WHERE (id = ?) " +
"LIMIT ?"; //limit
var var_arr = [id, limit];
var query = connection.query(query_str, var_arr, function (err, rows, fields) {}
//SQL query ...
return next();
}
app.get(url_path, respond);
}
The HTTP GET URL is http://127.0.0.1/read_sw?id=51&limit=1
The error reported is that the query is not properly formed. The actual query looks like this;
SELECT table.sw_type,
FROM users
WHERE (id = 51)
LIMIT '1'
I think the problem is LIMIT '1'. I think the solution is to make the query look like this;
SELECT table.sw_type,
FROM users
WHERE (id = 51)
LIMIT 1
How can the node.js code be modified?
This is not about mysql...
Anything in req.query is a string :
How about
var var_arr = [id, parseInt(limit)];
You can also use
var limit = Number(req.query.limit);