json into mysql using node.js - mysql

i trying to insert json created in node.js into mysql,
but there is a error in syntax, i am not able to rectify the error,
any help will be appreciated
my code
flowController.on('2', function (_selfid,_participantId,_groupid,_allMemberContent)
{
var allMemberDetailSQL= "SELECT spFunAllMemberNotificationDetails("+ _selfid + "," + _participantId +") as groupparticipants";
console.log("allMemberDetailSQL"+allMemberDetailSQL);
client.query(allMemberDetailSQL,function(detailERROR,detailResult)
{
if (detailERROR)
console.log("detailERROR "+ detailERROR);
else
{
var detailstr='';
detailstr = JSON.stringify(detailResult);
console.log('detailResult :'+ detailstr);
console.log("detailResult "+detailResult[0].groupparticipants);
var otherArray = [detailResult[0].groupparticipants];
var _allMemberDetail = JSON.stringify({
selfid: _selfid,
groupid: _groupid,
anArray: otherArray
});
console.log("_allMemberDetail " +_allMemberDetail);
var allMemberDetail = "'"+_allMemberDetail+"'";
console.log("allMemberDetail "+allMemberDetail);
client.query("INSERT INTO cmNotification (notificationSenderId, notificationReceiverId)"+"VALUES('"+_selfid+"','"+ _allMemberDetail+ "');", function(err, rows)
{
console.log("error insert "+err);
console.log("rows insert"+rows);
//connection.release();
});
}
});
});
console output
allMemberDetailSQLSELECT spFunAllMemberNotificationDetails(20,16) as groupparticipants
detailResult :[{"groupparticipants":"userid:'15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''"}]
detailResult userid:'15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''
_allMemberDetail {"selfid":"20","groupid":"15","anArray":["userid:'15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''"]}
allMemberDetail '{"selfid":"20","groupid":"15","anArray":["userid:'15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''"]}'
detailResult :[{"groupparticipants":"userid:'16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''"}]
detailResult userid:'16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''
_allMemberDetail {"selfid":"20","groupid":"15","anArray":["userid:'16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''"]}
allMemberDetail '{"selfid":"20","groupid":"15","anArray":["userid:'16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''"]}'
error insert 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 '15',firstname:'pitu15',lastname:'',isfriend:'1',profilepicurl:''"]}')' at line 1
rows insertundefined
error insert 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 '16',firstname:'pitu16',lastname:'',isfriend:'0',profilepicurl:''"]}')' at line 1
rows insertundefined

Use built in parameters escaping to prevent sql injection attack. "INSERT INTO ... SET ?" also makes life easier:
client.query("INSERT INTO cmNotification SET ?", {notificationSenderId: _selfid, notificationReceiverId: _allMemberDetail}, function(err, rows) {
// ...
});

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

MySQL 5.6.41 errno 1064: Creating a MySQL query with variables

I have a (currently localhost, but soon to be through AWS) Node.JS server with Express and I'm trying to update an RDS instance through a MySQL query when I'm getting the following 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 ''history0' = 'http://localhost:3000/' WHERE id = 1' at line 1]
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: '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 \'\'history0\' = \'http://localhost:3000/\' WHERE id = 1\' at line 1',
sqlState: '42000',
index: 0,
sql: 'UPDATE infected SET \'history0\' = \'http://localhost:3000/\' WHERE id = 1;' }
The POST request causing the error:
app.post('/history', function(req, res) {
var hist = 'history' + 0;
var sql = 'UPDATE infected SET ? = ? WHERE id = ?;';
connection.query(sql, [hist, req.body[0].url, 1]);
});
I'm using hist as a variable because I plan to have it in a loop, but I wasn't sure if the way I'm declaring it here is causing the issue so I left it as is. req.body is the output of JSON.stringify() called on call to chrome.history.search(). So I'm trying to get the URL of the entry at index 0.
I've tried a direct call to connection.query with a hard-coded string as follows:
connection.query("UPDATE infected SET history0='google.com' WHERE id='1'");
and it successfully updates the database, so I figure there's an issue with how I'm using the question marks to insert variables hist and req.body[0].url into the query, but I can't figure out what the issue is.
try with double "??" for the keys, this way:
app.post('/history', function(req, res) {
var hist = 'history' + 0;
var sql = 'UPDATE infected SET ?? = ? WHERE id = ?;';
connection.query(sql, [hist, req.body[0].url, 1]);
});

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.

Node js insert Mysql doesnt work

this is part of the code i use
var insertedData = {
name: 'testname',
score: '1337'
};
connect.query('INSERT INTO table SET ?', insertedData, function(error, result){
and this is the error i got
{ [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 'table SET name = 'Hek', score = '12'' at line
1]code: 'ER_PARSE_ERROR', errno: 1064, sqlState: '42000',index: 0 }
table is a reserved word in MySQL. I'd advise to rename your table to something else. If this is absolutely not a possibility for you, you can escape it with backticks:
connect.query('INSERT INTO `table` SET ?', insertedData, function(error, result){