mysql - how to display error instead of throw err in nodejs - mysql

I have put some constraints in my mysql table and thus when a duplicate value is entered, it throws an error and the server shuts down.
What I want instead is that the server should keep running and I should display the error to the end user, so they know they are inputting a duplicate value and hence the error.
how do I do that?
here's my code.
i tried to change the code a bit by putting the render statement in the else option. i.e if it doesnt throw the error then page is rendered otherwise It would do a res.send(err).
is that possible??
here's the code for this
connection.query("INSERT INTO attendance_details(month_year,uan,name,days_present,real_basic_salary,other_allowances,gross_salary,ptax) VALUES ?",
[finalData], function(err) {
if (err){
throw err;
res.send(err);
}else{
var attendanceData = {monthyear :monthFromHTML,rows:rowsLength,uanarr:uanArr,designationarr:designationArr,
namearr:nameArr,finaldata:finalData,realbasicsalary:realBasicSalary,realgrosssalary:realGrossSalary,ptax:pTax,advance:advance};
//put database query for inserting values here
res.render('attendance-data.ejs', attendanceData);
}
connection.end();
});

Related

trigger code execution based on query results on node server

In a node server I run a query that can produce three different results:
return a row of data with status='A'
return a row of data with status='B'
return no rows
based on what the query returns, I have to perform different actions after. I.E. if scenario is 1 then update that record with status='B'. If scenario is 3 then insert a new record and so on.
I am looking for the correct syntax to use to check the three conditions.
My code is the following:
con1.query("<my query goes here>", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
If I want to check scenario 3 is it correct to check if(result.length==0)while to check scenario 2 or 3 if(result[0].status=='A') or if(result[0].status=='B')?
Will this always elaborate correctly? I am coming from PHP so I want to understand if my logics are correct:
con1.query("<my query goes here>", function (err, result, fields) {
if (err) throw err;
if(result.length==0){
//do something
}else if(result[0].status=='A'){
//do something else
}else if(result[0].status=='B'){
//perform another action
}
});

MYSQL stops function when no data is found? (node.js)

I am getting som data from my MYSQL database. It checks for the email and date to match the users email and chosen date, then it gets the matching rows data. It all works well if I use a date that exists in the table, but when I use a date that does not exists, I get a ER_PARSE_ERROR.
It looks like this:
let date = 27/09/2019
let sql = `SELECT weigh, temp, length, cat, date FROM reps WHERE email = 'test#gmail.com' AND date = ?`;
connection.query(sql, [date], (error, result, fields) => {
if (error) throw error;
//here I do some stuff
When the date is not in the database, I get this:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')'
If there is no date, it now crashes my whole function. Instead I just want it to not get anything and keep the function going.
I tried below but it is still crashing:
if (error) {
send.response('nothing');
}
Any idea how to solve this?
This is finally solved. The reason I got the ER_PARSE_ERROR: was because I hade some functions that relied on the MySQL output. When no rows from MySQL was shown, the error occurred. I solved it by saying if nothing then end response. This is the code:
if (error) { throw error;
} else if (!result.length) { //Checks if no results, then ends the response without doing anything, before it tried to do things when there was no result which caused the error.
return console.log('Date or email does not match any database rows');
response.end();
}

Knex.js verifying query results in server side code

I have a function that is supposed to check if a license plate already exists in my MySQL database, but on the then-promise-return the result comes as:
result: [object Object]. How do you actually get the response of this knex query and parse it to check for a license plate existing?
var licensePlateExists = function(licensePlate){
knex.select('plate').from('licensePlates').where({'plate': licensePlate}).limit(1).then(function(result){
console.log("Result: " + result);
if(!result){
return true;
}
return false;
}).catch(function(error) {
console.error(error);
});
}
I think I might have an error related to the query itself, but I tested the raw query string in MySQL CLI and it outputs the row as expected. Maybe ordering matters in the knex query builder?
P.S. This doesn't error, it executes all the way through.
Try with
knex.select('plate').from('licensePlates').where('plate', licensePlate)
Actually using count query would be better

Node.js MySQL mass insert operation fails

Below is my code for mass insert into my MYSQL Db
connectionPool.getConnection(function(err, connection){
if(err) {
winston.log('info', '------- ERROR while getting connection: ' + err.message);
connection.release();
return;
}
connection.query('INSERT INTO PollOptions (idPollOption, Option, PollId) values ?', [pollOptionsArray], function(err, rows){
if(err) {
winston.info('info', '----------------------- ERROR: ' + err);
connection.release();
return;
}
connection.release();
});
});
Where the pollOptionsArray is
[
["POPE1lrKXMy9Q","Adam","POLL4yrFXzkcX"],
["POPVy-StXGJcm","Mike","POLL4yrFXzkcX"],["POPNkMSFmGy97","Lucy","POLL4yrFXzkcX"]
]
The database table has the following columns
idPollOption, Option, PollId (all VARCHAR)
It gives me the following error:
ERROR: Error: ER_PARSE_ERROR: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the
right syntax to use near 'Option, PollId) values ('POPE1lrKXMy9Q',
'Adam', 'POLL4yrFXzkcX'), ('POPVy-StXGJ' at line 1
I even tried to hardcode my sql input like this:
var temp = [
['123', 'demian#gmail.com', 'POLLVJsBGIjYQ'],
['345', 'john#gmail.com', 'POLLVJsBGIjYQ'],
['567', 'mark#gmail.com', 'POLLVJsBGIjYQ'],
['678', 'pete#gmail.com', 'POLLVJsBGIjYQ']
];
But it still gives me the same error. I don't understand what I am doing wrong. Clearly my SQL syntax is incorrect at the values but what is the remedy?
I even tried to remove the '[]' in the pollOptionsArray and it gives me the same error.
Any idea what is going on here?
So there was no issue with my syntax. The problem was the column named "Option".
Apparently "Option" is a reserved keyword in MySQL and since I used it to name my column, it was giving me trouble.

Error executing UPDATE

I'm having a little trouble performing an update query with the node mysql2 module. I'm preparing the query using the '?' placeholder and then passing in the values like so;
socket.on('connection', function(client){
[...]
client.on('userjoin', function(username, userid){
run_db_insert("UPDATE users_table SET clientid = ? WHERE user = ?", [client.id, userid], function(){
console.log(client.id + ' <=> ' + userid);
});
[...]
});
Unfortunately, this is raising an error;
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''12345678' WHERE userid = ?' at line 1
The data isn't reflected in the database. For some reason, the code doesn't appear to be picking up the second question mark placeholder and so it's not passing the correct value (i.e. it's trying to find the userid of ?).
If I change the code to this;
run_db_insert("UPDATE users_table SET clientid = ? WHERE user = '" + userid + "'", [client.id], function(){
...then the update runs without error and is reflected in the DB. If I console.log both client.id and userid, the console correctly reflects these values.
My run_db_insert function is as follows;
function run_db_insert(sql, args, callback){
var mysql = svc_mysql2.createConnection({
// connection details
});
mysql.connect(function(err){
if(err){
console.log('Error connecting to DB: ' + err);
}
});
mysql.query(sql, [args], function(err){
if (err){
console.log(err);
return;
}
callback();
});
mysql.end();
};
I've had no problems performing SELECT or INSERT queries using multiple '?' placeholders (with a slightly modified function that has result in the line 11 of that function and then returns that in the callback), but I'm finding that UPDATE isn't correctly assigning all the parameters I'm passing in to it.
I think your problem is that you're wrapping your query replacement values in another array, so [[client.id, userid]] is being passed to mysql.query().
Try changing:
mysql.query(sql, [args], function(err){
to:
mysql.query(sql, args, function(err){