Trying to insert JSON into MySQL with Node.JS - javascript

using Node.JS I have a JSON output I've received from an API call. I'm trying to insert this JSON into MySQL but I keep getting the error message:
"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 'ANU' at line 1"
Why is it rejecting the input request and how can I rectify this?
Additionally, I'd rather include multiple fields such as CountryName and CityName - how could I do this?
When analysing the JSON file in node.JS
console.log(typeof JSON) returns the output [object Object]
I think this is causing the error above as it is not in the correct format.
Node.JS extract:
//MySQL
let con = mysql.createConnection(config);
con.connect(function(err) {
if (err) throw err;
console.log("Connected to MySQL!");
var sql = "INSERT INTO TEST1 (CountryName) VALUES ?";
var values = obj.LocationsResponse.Country[1].CountryName;
con.query(sql, values, function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
});
JSON extract (I have cleansed to keep it short):
obj = {"LocationsResponse":
{"Country":[
{"CountryName":"United Arab Emirates","CountryCode":"AE","City":[{"CityName":"Abu Dhabi","CityCode":"AUH"},{"CityName":"Dubai","CityCode":"DXB"}]}
,
{"CountryName":"Antigua","CountryCode":"AG","City":{"CityName":"Antigua","CityCode":"ANU"}}
,
{"CountryName":"USA","CountryCode":"US","City":
[{"CityName":"Albuquerque","CityCode":"ABQ",{"CityName":"Albany","CityCode":"ALB",{"CityName":"Amarillo","CityCode":"AMA",
{"CityName":"Anchorage","CityCode":"ANC"
}}}}]}
]}}

JSON has nothing to do with this error.
You just got the syntax for INSERT wrong.
You have:
INSERT INTO TEST1 (CountryName) VALUES ?
You should have:
INSERT INTO TEST1 (CountryName) VALUES (?)
MySQL also supports an alternative syntax:
INSERT INTO TEST1 SET CountryName = ?
Read https://dev.mysql.com/doc/en/insert.html for more on MySQL's INSERT syntax.

Related

how to pass result from MySql query to ejs in node js

I am creating a dashboard that displays a number of data in different charts (e.g. horizontal bars, pie charts etc.)
I am using node js as a backend, MySQL as database, and ejs to render the data to html page.
I have had MySQL queries ready to query different data. The problem that I am having when I need to encapsulate these MySQL queries inside the routing function and pass the results to ejs.
Here is the sample code
router.get('/participant-module',(req,res)=>{
let sql1 = dbModel.participant_per_module; // MySQL query string
let sql2 = dbModel.error_per_module; // MySQL query string
let count_emp = [];
let count_error = [];
db.query(sql1, (err, result)=>{
if(err) throw err;
count_emp.push(result);
});
db.query(sql2, (err, result)=>{
if(err) throw err;
error_count.push(result);
});
res.render('dashboard', {emp_count:count_emp, error_count:count_error}); // pass array to ejs
});
count_emp and count_error are display in different charts. But, here the count_emp and count_error are always null.
I have tried to search for similar problem in the forum and the cause seems to be db.query is async so it won't wait and thus when res.render send the data, emp_count and error_count are still null.
So does anyone have a workaround on this?
Thank you in advance
D
Your db.query calls and res.render are running asynchronously without waiting for the query result. What is happening is that, your first query is fired, then immediately your second query is fired, then immediately your router is returning the response. You are not waiting for the queries to retrieve the results. That's why your count_emp and count_error is [] every time the response is rendered.
Try this:
router.get('/participant-module',(req,res)=>{
let sql1 = dbModel.participant_per_module; // MySQL query string
let sql2 = dbModel.error_per_module; // MySQL query string
let count_emp = [];
let count_error = [];
db.query(sql1, (err, result)=>{
if(err) throw err;
count_emp.push(result);
db.query(sql2, (err, result)=>{
if(err) throw err;
error_count.push(result);
res.render('dashboard', {emp_count:count_emp, error_count:count_error}); // pass array to ejs
});
});
});
PS: You should try to avoid over-nesting of callbacks. It is commonly referred as callback hell. Some common ways are: 1. Using promises 2. Using named functions

How to update a record based on the primary key PUT method Express node.js

I am a bit confused on how to use the put statement in node js at the moment, currently I am using:
app.put("/cars/:id", (req, res) => { //get record based on id (uuid) e.g. http://localhost:3000/cars/a5ad957c-7d1b-11eb-8a21-0653a157c10e
connection.connect(function(err) {
connection.query(`UPDATE main.cars SET manufacturer= '${req.params.manufacturer}', WHERE id = '${req.params.id}')`, function(err, result, fields) {
if(err) res.send(err);
if(result) res.send(result);
});
});
});
But I receive the following error in postman:
{
"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 'WHERE id = 'a5ad957c-7d1b-11eb-8a21-0653a157c10e')' at line 1",
"sqlState": "42000",
"index": 0,
"sql": "UPDATE main.cars SET manufacturer= 'undefined', WHERE id = 'a5ad957c-7d1b-11eb-8a21-0653a157c10e')"
When I use the following query:
http://localhost:3000/cars/a5ad957c-7d1b-11eb-8a21-0653a157c10e?manufacturer=prius
The simple answer here is that strings in SQL must be quoted with ' characters.
… however while adding them is a simple fix, it would leave you vulnerable to SQL injection attacks.
Look up how to use parameterized queries in whatever SQL library is giving you your connection object.

Javascript concatenation error or Node.js MSSQL module adding extra quote marks?

I am trying to send a query to SQL Server using Node.js and the MSSQL module
const dataSend = new Promise((resolve, reject) => {
sql.connect(config).then(pool => {
myQuery = "INSERT INTO persoane ([name], telefon) VALUES ('"+req.body.name+"','"+req.body.telefon+"')";
resolve(pool.request().query(myQuery));
reject('Error in dataSend');
})
});
Using SQL Server Profiler, I can see the query being sent to SQL Server as:
'INSERT INTO persoane ([name], telefon) VALUES (' 'John' ',' '11111111111' ')'
The double quotes on VALUES produce a error. How to write just one single quote in the final query?
Did I concatenate wrong or is something from MSSQL?
Thank you!

NodeJS and MySQL: Data not being stored in a variable

I am trying to extract data from the following MySQL query and storing it in a variable so I can use it but when I console log it to see if data was successfully pulled, I see a bunch of irrelevant stuff and not the data. Any help will be greatly appreciated it.
const body = req.body
const varQuery = await pool.query('SELECT id, name, email FROM registration WHERE email = ?', [body.email])
console.log(varQuery)
If you are using mysql, you have to pass callback as an argument, instead of using the async/await syntax. It would look something like that:
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});```

MongoDB Error: Cannot create property '_id' on string

I'm using Node.js and Express on Heroku, with the MongoDB addon.
My database connection works fine and I can successfully push some data in, but not other.
Here is the database connection:
mongodb.MongoClient.connect(mongoURI, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || dbport, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
I can successfully push my Twitter API response into the database like this:
db.collection(TWEETS_COLLECTION).insert(data);
('data' is just a JSON variable)
But when I try to push another JSON variable into the database in the same method, I get an error. Code:
var jsonHash = '{"hashtag":"","popularity":1}';
var objHash = JSON.parse(jsonHash);
objHash.hashtag = req.body.hashtag;
JSON.stringify(objHash);
collection(HASHTAG_COLLECTION).insert(jsonHash);
And the error:
TypeError: Cannot create property '_id' on string '{"hashtag":"myhash","popularity":1}'
at Collection.insertMany...
...
Any ideas what I'm doing wrong?
I don't know where you are getting the jsonHash variable from but I think you are doing unecessary JSON-handling here. You are also inserting the wrong variable, you want to insert objHash which is a valid object to insert, now you are inserting jsonHash which is just a string. JSON.stringify(objHash); is not doing anything as you are not saving the JSON returned from the function. I think you want something like this?
var objHash = {
hashtag: "",
popularity:1
};
objHash.hashtag = req.body.hashtag;
collection(HASHTAG_COLLECTION).insert(objHash);
jsonHash is still a string. May be you want to save objHash instead without JSON.stringify ?

Categories

Resources