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

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

Related

Insert JSON object data to MySQL using Node.JS

I want insert a JSON object into MySQL in Node.js server, this is the code
let id = 1
let date = new Date().toJSON().slice(0,10).replace(/-/g,'/');
let sql ='INSERT INTO case_record (case_details,gen_date,case_id) VALUES('+caseDetails+','+date+','+id+')'
console.log(sql)
con.query(sql,function(err, result, fields){
if(err) throw err;
res = result;
console.log(res)
});
This is the caseDetails data
let caseDetails = {
caseData,
patData,
notifData,
primecData,
refData}
Each of the object in the caseDetails is JSON object also.
When I excute, the error return is
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 '[object Object],2019/04/22,1)' at line 1
How to fix this problem?
Your SQL syntax is wrong to cause parsing error.
Why don't u follow this correction?
...
let sql ='INSERT INTO case_record(case_details,gen_date,case_id) VALUES(?,?,?)';
con.query(sql, [caseDetails,date,id] ,function(err, result, fields) {
...
});
Hope to get helped.

MariaDB SQL in Node throwing ER_PARSE_ERROR when I try to query an array of data

I'm trying to feed an Array of data formatted like this
[ 3717003570,'HYDRAULIC ACTUATOR','DIAMEC','EXPLORATION',2,16071.59]
and its returning the error saying
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the
right syntax to use near '3717003570, 'HYDRAULIC ACTUATOR', 'DIAMEC',
'EXPLORATION', 2, 16071.59' at line 1
While when I try to manually insert the data with a query in SequelPro it isn't throwing any sort of error
EDIT: Whole statement
var query = "INSERT INTO products (ITEMNO, DESCRIPTION, MODEL, CATEGORY, QTY, PRICE) VALUES ?";
con.query(query, values, (err, results)=> {
if (err) throw err;
console.log("Sucess, Rows Affected:" + results.affectedRows);
})

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.

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

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

Not able to insert data into table using Nodejs

exports.creategroup= function(callback,name,email,firstname)
{
// var connection=pool.getConnection();
var connection=connect();
console.log(email);
console.log(firstname);
var query="CREATE TABLE "+name+"(membername varchar(50) NOT NULL,email varchar(50) NOT NULL)";
var query1="INSERT INTO'"+name+"'(membername,email) VALUES('"+email+"','"+firstname+"')";
console.log(query);
connection.query(query,function(err,result){
if(err)
{
console.log("ERROR:"+err.message);
}
else
{
if(result.length!==0)
{
console.log("DATA : "+JSON.stringify(result));
callback(err, result);
}
else
{
callback("Invalid Username", result);
}
}
//pool.returnConnection(connection);
});
//The insert into query gives an error. I can't figure out what syntax error i have made. Could someone please help. The table is being created. The error I am facing in the insert is
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 ''sad'(membername,email) VALUES('hunur','Sachin
Mallikarjun')' at line 1
here sad was passed as the argument for table name
You've put the table Name in ' ticks, that's not valid. Below will work:
var query1="INSERT INTO "+name+" (membername,email) VALUES('"+email+"','"+firstname+"')";
Please note that you absolutely shouldn't run a query like this as it is vulnerable to mysql injection. Use the escaped query node-mysql offers instead.
var query = "INSERT INTO ?? (??,??) VALUES (?,?)";
var values = [name,'membername','email',firstname,email];
mysql.query(mysql.format(query, values), function(err,result,tableInfo){/*...*/})
Like this, node-mysql prepares the query for you. Every ?? represents a table or column name while every ? stands for a value to be inserted. You can verify this by
console.log(mysql.format(query,values));