Fastest way to get JSON object into mysql using node - mysql

Using a prior example? How could I insert/update a mysql table using
a JSON object without manually naming the table column headers? And insure it async.
var mysql = require('node-mysql');
var conn = mysql.createConnection({
...
});
var values = [
{name:'demian', email: 'demian#gmail.com', ID: 1},
{name:'john' , email: 'john#gmail.com' , ID: 2},
{name:'mark' , email: 'mark#gmail.com' , ID: 3},
{name:'pete ' , email: 'pete#gmail.com' , ID: 4}
];
// var sql = "INSERT INTO Test (name, email, n) VALUES ?";
conn.query(sql, [values], function(err) {
if (err) throw err;
conn.end();
})

You could do something like this:
for(var i = 0; i < values.length; i++){
var post = values[i]
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
// Finish
});
}
EDIT
This is how you inserts multiple 'posts' at once.
INSERT INTO posts (type, details)
VALUES
('Helen', 24),
('Katrina', 21),
You would have to loop through the first value to get the names like this.
var names = [];
for(name in values[0]){
names.push(name);
// That would give you name, email, id
}
Then you would have to create your own string to insert.
var newvalues = [];
for(var i = 0; i < values.length; i++){
newvalues.push('(' + values[i].join(',') + ')');
}
Then to execute the query:
connection.query('INSERT INTO posts (' + names.join(',') + ') VALUES ' + newvalues.join(',') , function(err, rows, fields) {
// Result
});
You would have to test the code yourself, this is just how you would do it.

Look at the 'Custom Format' part here. If you notice, this example using named placeholders in the query, allowing you to pass an object, and the placeholders are replaced with the matching attributes from the object. I've also pasted the relevant section for clarity:
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });

You could create a small function that maps an array with that format to an insert statement.
You can easily loop through the fields and use some string concatenation.

Better option is (using MySQL Connection):
app.get('/yourcontroller/:id', function (req, res) {
var id = req.params.id;
var dataUpdate = req.body;
connection.query(
'UPDATE yourtable SET ? Where ID = ?',
[dataUpdate, id],
function (err, result) {
if (err) throw err;
console.log('Updated data ! Changed ' + result.changedRows + ' rows');
}
);
});

Related

nodejs mysql pagination via prepared Query statement returns error forEach property undefined

The nodejs code below works fine when used to retrieve content from database. now when i tried to get content via pagination as per code below via prepared query statement
db.query('SELECT * FROM posts1 limit row=?, rowperpage=?', [parseInt(row),parseInt(rowperpage)], function (error, results, fields) {
});
it returns error "cannot read property forEach of undefined"
below is the full code
exports.display = function (req, res) {
var row = 0;
var rowperpage = 3;
console.log(row);
console.log(rowperpage);
var objs1 = [];
db.query('SELECT * FROM posts1 limit row=?, rowperpage=?', [parseInt(row),parseInt(rowperpage)], function (error, results, fields) {
// db.query('SELECT * FROM posts1', function (error, results, fields) {
results.forEach(function(row) {
var id = row.id;
var title = row.title;
var content = row.content;
var shortcontent = row.content;
var link = row.link;
objs1.push({
id: id,
title: title,
shortcontent: shortcontent,
content: content,
link: link,
});
});
res.end(JSON.stringify(objs1));
});
}
Adding the following code below, solve the issue
//parse int Convert String to number
let startNum = parseInt(row);
let LimitNum = parseInt(rowperpage);
var objs1 = [];
db.query("SELECT * FROM ?? limit ? offset ?", ["posts1",LimitNum,startNum], function (error, results, fields) {
Thanks

How to insert json into mysql using node js?

var express = require('express');
var app=express();
var length;
var affiliate = require('flipkart-affiliate');
var url = require('url');
var moment=require('moment');
var mysql = require('mysql');
var body;
var getUrl;
var product;
var offer;
var offer1;
var offer2;
var offer3;
var test1;
var test2;
var test3;
var title=[];
var description=[];
var startTime=[];
var endTime=[];
var json={};
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'coupontest'
});
var client = affiliate.createClient({
FkAffId: 'anandhkum',
FkAffToken: 'eb030998c556443087d3b1a27ac569d0',
responseType: 'json'
});
client.getCategoryFeed({
trackingId: 'anandhkum'
}, function(err, result,getUrl){
if(!err){
body=JSON.parse(result);
getUrl=body.apiGroups.affiliate.apiListings.food_nutrition.availableVariants["v1.1.0"].get;
client.getProductsFeed({
url: getUrl
}, function(err, result){
if(!err){
}else {
console.log(err);
}
});
}
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.get('/',function (req,res) {
client.getAllOffers(null,function(err, resp) {
if (!err) {
offer = JSON.parse(resp);
test1 = offer.allOffersList.length;
res.send(offer);
for(var i=0;i<test1;i++){
description[i]=offer.allOffersList[i].description;
startTime[i]=offer.allOffersList[i].startTime;
endTime[i]=offer.allOffersList[i].endTime;
}
var stmt = "INSERT INTO offers(description,start_time,end_time) VALUES (?, ?, ?)";
connection.query(stmt, [description,startTime,endTime], function (err, result) {
if (err) throw err.message;
console.log("Number of records inserted: " + result.affectedRows);
});
}
else {
console.log(err);
}
});
});
app.listen(3000);
console.log("Listening to port 3000");
the code is about getting the offer details as json data from flipkart.com and store it into the mysql table.
But I'm getting the error
throw err; // Rethrow non-MySQL errors
ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1
I tried using many sql syntax but it's showing the above error
Can anyone help me on solving the above error?
Try doing it this way, as I can see you want to insert multiple result at once so need to pass an array values which I have made in following query also the error "ER_WRONG_VALUE_COUNT_ON_ROW" is due to incorrect no of ? that you were passing in the query as you need to insert multiple no of rows so you need to make sure you get correct ? count.
var queryString = "";
var insertString = "(?,?,?),";
var values = [];
for(var i=0;i<test1;i++){
description[i]=offer.allOffersList[i].description;
startTime[i]=offer.allOffersList[i].startTime;
endTime[i]=offer.allOffersList[i].endTime;
values.push(description[i],startTime[i],endTime[i]);
queryString = queryString + insertString;
}
queryString = queryString.substring(0, queryString.length - 1); // is used to remove last ',' which will get inserted while we are creating queryString
var stmt = "INSERT INTO offers(description,start_time,end_time) VALUES " + queryString ;
connection.query(stmt,values, function (err, result) {
if (err) throw err.message;
console.log("Number of records inserted: " + result.affectedRows);
});

Node JS mySQL tripple query and lost of information

In my application I have a two different tables related to each other by ID of the first one (one to many relation). It should first collect the data from the frontend-side by in JSON format which looks like this:
cancellation = {
name: someting
id: someting
rule =
[
{someting}, {something}, {something}
]
}
One table would be for cancellation and the second one for the rules. If I want to put those information in this order I need first insert one record for cancellation. Then make a query to find out what is an ID of this record in the database and after that insert all rules using this ID as a foreign key. But since Node JS is asynchronous before I fetch the information about the ID of the record program stars to execute rest of the code and consider this variable as undefined.
app.post('/databaseSend/cancellation', function(req,res){
var cancellationReceived = req.body;
var cancellationID;
var rules = [];
var cancellation = [];
cancellation[0] =
[
cancellationReceived.name,
cancellationReceived.id
]
// inserting data into cancellation table
connection.query("INSERT INTO cancellations (name, User_ID) VALUES ?", [cancellation],
function(err,results){
if(err){console.log(err)}
}
)
//fetching ID of the current record
connection.query("SELECT id FROM cancellations WHERE User_ID = ? AND name = ?", [cancellationReceived.id, cancellationReceived.name],
function(err, results){
var cancellationID = results[0].id;
});
//assigning ID to use it as a foreign key
for(var i = 0; i < cancellationReceived.rule.length; i++)
{
rules[i] =
[
cancellationReceived.rule[i].daysBefore,
cancellationReceived.rule[i].fee,
cancellationReceived.rule[i].type,
cancellationID
]
}
for(var i = 0; i < rules.length; i++)
{
console.log(rules[i]); // ID is undefined
}
});
How can I solve this problem? I tried to use setTimeout for pausing my code but it did not change anything.
And I use this node module for mysql - > https://github.com/mysqljs/mysql
The best way to solve this problem is RTFM.
connection.query('INSERT INTO cancellations (name, user_id) values ?', [cancellation], function(err, results) {
if (err)
return console.error(err);
// See https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row
var cancellation_id = results.insertId;
// Generate sql for rules, join them by ; and execute as one query
// See https://github.com/mysqljs/mysql#multiple-statement-queries
connection.query(sqls, function(err) {
if (err)
return console.error(err);
// Send response here
});
})

Unable to get value from JSON after mySQL

var sender_username = req.session.user_id;
var recipient_username = req.body.recipient_username;
var content = req.body.content;
var sql = ' SELECT sender_username, recipient_username, COUNT(recipient_username) as count FROM message WHERE sender_username = "'+sender_username+'" AND recipient_username = "'+recipient_username+'" GROUP BY sender_username LIMIT 1 ';
var message_no = 0;
var data;
connection.query(sql, function(err, result) {
if (err) {
res.send(err);
}
else {
data = result;
// res.send(data); < - this works
// res.send(result); <- this works
// res.send(result.count); <- undefined
}
});
res.send(data); // undefined (can't seem to save to variable after connection.query())
The res.send(result); seems to work. It gives:
[{"sender_username":"sender","recipient_username":"recipient","count":2}]
I am just trying to get the value for count and save that to a variable, but things like result.count are returning undefined for some reason.
It's because the JSON is an array, so you should access it like the following
res.send(result[0].count);

How to get value from unknown object property?

I have an issue with extracting value from object. I want to check if my SQL table have the asked row:
var checkRow = function(connection,chekedColumn,chekParam, checkVal){
connection.query('SELECT EXISTS(SELECT '+ chekedColumn +' FROM asterisk.users where ' +chekParam+'='+checkVal+')', function (err, rows) {
if(err) console.log('SQL suerry error')
else {
console.log(rows[0]); // output: { 'EXISTS(SELECT id FROM asterisk.users where name=1600)': 1 }
return (rows[0]);
};
});
};
but returned value from query is an object, and return(rows[0]) give just [object object] output. How can I extract value of this object?
You can use
Object.keys(obj)
to get the values of the object. See api reference for more info.
EDIT:
Just to elaborate abit more on this... how you'd go about getting it out is this.
// get the keys of the source
var keys = Object.keys( source );
// loop through the keys
for ( var i = 0; i < keys.length; i++ ) {
var key = keys[i];
var value = source[key];
//do something with value
}
The output is an object which you don't know. So try either:
console.log("Result: %j", rows[0]);
console.log(JSON.stringify(rows[0]));
console.log(require('util').inspect(rows[0], false, null));
to view the structure. After you know the keys, use it to access the data.
Thanks all for helps and for your ideas. Dmitry Matveev help me to understand how to identify object properties(Objekt.keys()). And thanks to user568109 for reminding of asynchronous function, so I use callback. Final code:
var checkRow = function(connection,chekedColumn,chekParam, checkVal,callback){
connection.query('SELECT EXISTS(SELECT '+ chekedColumn +' FROM asterisk.users where ' +chekParam+'='+checkVal+')', function (err, rows) {
if(err) console.log('SQL suerry error')
else {
var keys=Object.keys(rows[0]);
keys.forEach(function(key) {
callback(rows[0][key]);
});
};
});
};
And for using this functions we need to call it like:
checkRow(connection,'id','name',name,function(value){
console.log(value)
})