How To Pass Objects From Node To Mysql - mysql

The problem I'm having is with passing the object from Node.js to the database (MySQL).
currently, I'm using the INSERT method which only allows me to pass strings, if I try to pass an object I get an error
Here is what I'm using right now :
let new_movie_data = `INSERT INTO testing (name, last) VALUES ('Jhonee','Mel')`
connection.query(new_movie_data, function (err, result){
if(err) throw (err)
})
This is what I get from react and want to send to the database :
{
name:"Jhonee",
last:"Mel"
}
trying to put this in the "VALUES" will cause an error.
Thanks :D

You could parse the JSON in to its components:
jsonObj = JSON.parse(stringFromReact);
const new_movie_data = 'INSERT INTO testing (name, last) VALUES (?, ?);
connection.query(new_movie_data, [jsonObj.name, jsonObj.last], function (err, result){
if(err) throw (err)
});

Related

Bulk insert in mySQL using node.js not working

Referring to this thread How do I do a bulk insert in mySQL using node.js I have written the below code
const values = [
['e33b3c34923500e6', 'The Office', '330248b39a55d82a', '690db8528741c098'],
['e33b3c34923500e7', 'Prison Break', '330248b39a55d82a', '690db8528741c098']
]
let sql = `INSERT INTO Result (resultId, result, submissionId, questionId) VALUES ?`
connection.query(sql, [values], (err, res) => {console.log(err)
console.log(res)
})
Normal single inserts work with the given values but whenever trying to bulk insert like above I get the following error:
return await usedQueryRunner.query(query, parameters); // await is needed here because we are using finally TypeError: usedQueryRunner.query is not a function

NodeJS MySQL concat queries with responses from many model queries to one controller call

I'm having problems understanding the async methods on nodejs.
I have this fragment of code in my controller:
app.get(basePath, function (req, res, next) {
model.generateDB(function (modelErr, modelRes) {
if (modelErr) console.log('Error: ' + modelErr);
next(res.send(modelRes));
});
});
this fragment of code for the model:
generateDB: function (next) {
BDManager.query(
'INSERT INTO tableName' +
'(field1, field2) VALUES ("a", "b")',
function (err, res) {
next(err, res);
});
}
and this fragment of code for the db manager
query: function (sql, next) {
var con = mysql.createConnection(config.MySQL);
con.query(sql, function (err, res) {
if (err) next(err, null);
next(null, res);
});
con.end();
}
It works fine for me. the question is how may I have multiple queries with they're responses in the model with only one controller call, like the example (that not works):
BDManager.query(
'INSERT INTO tableName' +
'(field1, field2) VALUES ("a", "b")',
function (err, res) {
next(err, res);
});
BDManager.query(
'INSERT INTO tableName' +
'(field1, field2) VALUES ("a", "b")',
function (err, res) {
next(err, res);
});
BDManager.query(
'INSERT INTO tableName' +
'(field1, field2) VALUES ("a", "b")',
function (err, res) {
next(err, res);
});
the idea could be to get an array of errors and responses, but I don't know how to send it when all queries finish. I tried with the .then, but it seems that doesn't works (The error I get using .then is "can't use then on null").
Another solution could be to concat many queries in one, but I tried with "; " separator and doesn't works for me.
So this is using callbacks (.then is for promises). You could create a promise wrapper around it that would let you promisify it and then you could await them or use promise.all if you wanted to run them in parallel.
For example:
function promiseQuery(query, params) {
return new Promise((resolve, reject) => {
BDManager.query(query, params, function (err, res) {
if (err) return reject(err);
return resolve(res);
});
});
}
let arrayOfResponses = await Promise.all([
promiseQuery(query1, params1),
promiseQuery(query2, params2),
promiseQuery(query3, params3),
]);
Just a few things about that - you probably should be inserting values via parameterized inputs. Your SQL library should support that
Also an error will throw a rejection on this. If you want to catch those errors and push them to an array, you could do that as well with a .catch handler.
If you're not using async/await or a version of node that's compatible, you can also do:
Promise.all([]).then(arrayOfResponses => {});
As well and that will give you the array of the responses for any promises you pass in to promise.all.
There are tons of articles on how to use Promises and how they work but that should get you started.

How to insert an object into SQL using nodejs

I'm trying to insert some string variables into a DB with nodeJS following parsing the text from the DOM.
I'm using cheerio for that , here's an example that I'm trying to write to my db, it type tests as a string and outputs a score out of 10 e.g 3.5 out of 10.
var kf = $('span.glyphicons.glyphicons-star').attr('title')
My code for the sql is as follows, I can't seem to find anywhere how to define the variable in the sql query line:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO juice (ratescore) VALUES ('" + con.escape(kf) + "')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});

Node mysql bulk insert with express array parameter

I've come across a situation where I need to use a bulk insert with my Node project.
This of course has already been answered here: How do I do a bulk insert in mySQL using node.js
However, I have an express project which I use to create an api. The parameters are turned into an array and I'm having trouble using that array with a bulk insert. Whenever I try to use that route, I get an error of Error: ER_WRONG_VALUE_COUNT_ON_ROW: Column count doesn't match value count at row 1
After some digging I found that it tries to insert:
['foo', 'bar', 'test']
When I need it to insert:
['foo']
['bar']
['test']
Anyways, here's the whole code:
Route
router.post("/", function (req, res, next) {
db.query(
"REPLACE INTO user (`Name`) VALUES (?)",
[req.query.array],
function (error, response) {
if (error) throw error;
console.log(response);
}
)
});
Route Caller
let requestUrl = "http://localhost:3000/user?";
// External api request which returns a list of users
for (let i = 0; i < body.users.length; i++) {
requestUrl += `array=${body.users[i]}&`
}
let addUserRequest = {
url: requestUrl,
method: "POST"
};
request(addUserRequest, function (error, response, body) {
console.log(body);
});
The url that is generated is:
http://localhost:3000/user?array=foo&array=bar&array=test
Try this,
var datatoDB = [];
req.query.array.forEach(function(entry) {
console.log(entry);
datatoDB.push([entry]);
});
Here we are trying to convert this ['foo', 'bar', 'test'] to this [["foo"], ["bar"], ["test"]].
Now, use datatoDB in your function.
router.post("/", function (req, res, next) {
db.query(
"REPLACE INTO user (Name) VALUES ?",
[datatoDB],
function (error, response) {
if (error) throw error;
console.log(response);
}
)
});

Node.js - mysql: Bad field Error

I parse a big csv and insert row per row into my mysql tables.
After parsing I do a lot of calculation and transforming and save it to a new Object
obj.push({
"ID": value.id,
"col1": value.calc1,
... });
After the Object is complete I do:
async.forEach(obj, function (Insertobj, callback) {
var query = conn.query('INSERT INTO table SET ?', Insertobj);
},function (err){
if (err) {
console.log(err);
console.log('failed to process');
}}
After running through the obj I get =>
Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'field list'..
But he inserts the complete Object into my table! I don't have any column called NaN or empty cols. How can I debug it? I try to set the console.log to err.sql, but he print "undefined". Using debug:true in connection didn't help me.
I think you have misunderstood how escaping mysql values works using the node js module. The error is due to you not specifying what column you want to update. In addition to this, the escaped values should be filled in using an array instead of an object. With values being in the order they are escaped in the query. Your code could look as follows:
valuesarray.push([
value.id,
value.calc1
]);
async.forEach(valuesarray, function ( insertarray, callback ) {
var query = conn.query('INSERT INTO table SET ID = ?, col1 =
?', insertarray);
},function (err){
if (err) {
console.log(err);
console.log('failed to process');
}
});