HOw can i send null value to database in node.js?
I am using MySql Package for node JS
and I have some null values to insert which I want to be stored in database as DBNull.Value( as in asp.net) and not as "null" or " ".
Also, I cannot skip any value to insert.
My code below:
var query=connection.query("insert into user_details(user_id,username,screenname,firstname,middlename,lastname,about_me,color_code,Gender,hobbies,occupation,member_of_group,profile_pic,address1,address2,city,pincode,phonenumber,EmailId1,EmailId2,createdate,updatedate) values('"+json.user_id+"','"+ json.username+"','"+json.screenname+"','"+json.firstname+"','"+json.middlename+"','"+json.lastname+"','"+json.about_me+"','"+json.color_code+"','"+json.Gender+"','"+json.hobbies+"','"+json.occupation+"','"+json.member_of_group+"','"+json.profile_pic+"','"+json.address1+"','"+json.address2+"','"+json.city+"',"+json.pincode+",'"+json.phonenumber+"','"+json.EmailId1+"','"+json.EmailId2+"','"+json.createdate+"','"+json.updatedate+"');",function(err,result){
if(!err){
connection.destroy();
callback(result);
}
else
{
console.log(err);
callback('error');
}
});
How can I do that???
First of all, you shouldn't directly concatenate (especially user submitted) values for security reasons and it's just plain tedious when you have a lot of concatenation going on.
Try this instead which makes it easier to work with and properly escapes your values:
connection.query('INSERT INTO user_details SET ?', json, function(err, result) {
connection.destroy();
if (err)
console.log(err);
callback(err, result);
});
or manually specify the values if the keys in the data source do not match up with column names:
var values = {
user_id: json.id,
username: json.user,
// ...
};
connection.query('INSERT INTO user_details SET ?', values, function(err, result) {
connection.destroy();
if (err)
console.log(err);
callback(err, result);
});
Secondly, typically callbacks use "error-first", so passing a real error object as the first argument is better.
Related
I have this INSERT query. It does create a record in the table, but "client" value is 0, and "short" value is null. However, all of the console logs show the correct data. I'm assuming this is a simple syntax error in my use of the question marks. But I can't find that, or seem to get it to work using just variable names either. Any help is appreciated.
app.put("/audit/create", function (req, res) {
console.log("It is getting to the route");
const client = req.body.client;
const short = req.body.short;
console.log(`client: ${client}`);
console.log(`short: ${short}`);
connection.getConnection(function (err, connection) {
connection.query(
`INSERT INTO audits (client, short)
VALUES (?, ?)`,
[
{
client: client,
},
{
short: short,
},
],
function (error, results, fields) {
if (error) throw error;
res.json(results);
console.log(`Audit has been created`);
}
);
connection.release();
});
});
I've also tried using the variables names of ${client}, ${short} in place of the questions marks... and that still gives me the same result. However the console logs that render ${client} and ${short} do log the correct data I'm expecting to see.
Why are you passing objects as the values to the query? Try just:
connection.query(
'INSERT INTO audits (client, short) VALUES (?, ?)',
[ client, short ],
function ...
I have a SQLite database I am trying to add data to with the sqlite3 package. My query is as follows, and works in the SQLite command line.
'INSERT INTO `EVENTS`(`ID`,`EventName`,`EventSociety`,`BookerName`,`BookerEmail`,`BookerStudentID`,`BookerPhone`,`TimeStart`,`TimeEnd`,`EquipmentList`,`EventSearchYear`,`EventSearchMonth`,`EventSearchDay`) VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);';
And I'm using this code to insert to the database in node.
db.run("begin transaction");
let sql = 'INSERT INTO `EVENTS`(`ID`,`EventName`,`EventSociety`,`BookerName`,`BookerEmail`,`BookerStudentID`,`BookerPhone`,`TimeStart`,`TimeEnd`,`EquipmentList`,`EventSearchYear`,`EventSearchMonth`,`EventSearchDay`) VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);';
console.log(sql);
db.run(sql,(err) => {
res.send('ok');
});
db.run("commit");
Trying this in node hard crashes, with a Illegal instruction: 4. However, it is only happening on two tables, both with over 5 fields, in my database, and not any other smaller ones. Is there a character limit I'm unaware of?
To avoid crash, we need to handle error as below:
Example
The line db.run(sql, params, function (err) { in below example:
let sql = `INSERT INTO Users(id,firstName,lastName,email,password,permissionLevel) VALUES (?,?,?, ?,?,?)`;
let params = [uuid4(), "fn1", "ln1", "a#a2.com", "pwd1", 0];
db.run(sql, params, function (err) {
if (err) {
console.error("Error: Insert failed: ", err.message);
console.error("Error: Full error: ", err);
return;
}
console.log("insert success");
});
I am playing with Express.js and MySQL. I am trying to create a route in order to display data via API.
In my database, I have a price field and I am trying to display all properties in the a price range.
SELECT * FROM properties
WHERE price BETWEEN 10000 AND 20000;
In my model.js file I set up like this:
Property.findBy = (valueMin, valueMax, result) => {
sql.query(`SELECT * FROM properties WHERE price BETWEEN ${valueMin} AND ${valueMax}`, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
if (res.length) {
console.log("No price: ", res[0]);
result(null, res[0]);
return;
}
result({ kind: "range" }, null);
});
};
In my controller.js file
exports.findMaxi = (req, res) => {
Property.findBy(req.params.valueMin, req.params.valueMax, (err, data) => {
if (err) {
if (err.kind === "not_found") {
res.status(404).send({
message: `Not found property for range ${req.params.valueMin} and ${req.params.valueMax}`
});
} else {
res.status(500).send({
message: "Error found property for range " + req.params.valueMin + req.params.valueMax
});
}
} else res.send(data);
});
};
And finally, my routes:
app.get("/properties/:valueMin&valueMax", propertis.findMaxi);
This route doesn’t work. I don’t know how to solve this problem. Can someone offer assistance?
I think it's because your route is like
app.get("/properties/:valueMin&valueMax", propertis.findMaxi);
you'll only be able to pass 1 value and the other is the string "&valueMax", so you can't change the value of valueMax... for example, if you want to have valueMin = 100, the query is like GET /properties/100&valueMax.
So, each value you want to pass in this way, use ':' before each variable, like
app.get("/properties/:valueMin&:valueMax", propertis.findMaxi);
and a query like //GET /properties/100&200 will work
But I think it's better to pass the variables as query params GET /properties?min=100&max=200
You most likely want to pass min and max as query parameters.
// GET /properties?min=10000&max=20000
console.log(req.query.min) // => '10000'
console.log(req.query.max) // => '20000'
The way you did is that you have one value that you can access with req.params and it is valueMin&valueMax (I don't think it is even valid to have a variable that contains & character).
You could have a route like /properties/:min/:max to access those two separately, or just use query parameters which is made for that purpose
I've been working on an application which allows me to add companies to a database. Originally my code was pure spaghetti, so I wanted to modularize it properly. For this purpose, I added routes, a controller and a dao.
This is how my code looks right now
Routes
app.post('/loadcompanies', (req, res)=> {
companiesController.loadcompany(req.body, (results)=>{
console.log(results);
res.send(200, "working!");
})
})
Controller
module.exports.loadCompany = (body, callback)=>{
companiesDao.loadCompany(body, callback);
}
Dao
module.exports.loadCompany = (company, callback)=>{
MongoClient.connect(conexionString, (err, database) => {
if (err) console.log(err);
db = database;
console.log(company);
db.collection('companies').insert(company, (err, result)=>{
callback({message:"Succesfully loaded company", company:result});
});
})
}
My current concern is that working with errors when modularizing like this is confusing. I tried adding a try-catch method around the db insert and throwing and error if there is one, but that doesn't seem to work. Other things I've tried is returning the error in the callback, like this:
if (err) callback (err, null);
but I end up getting a "Can't set headers after they are sent." error.
How would you handle errors in this situation? For example, in the case that someone tries to add a duplicate entry in an unique element.
You should be able to simply do the error checking inside the callback for the insert function:
db.collection('companies').insert(company, (err, result)=>{
if (err) {
callback(err, null);
return;
}
callback(null, {message:"Succesfully loaded company", company:result});
});
If you get an error like you say, that's probably because the database is actually returning an error. You could also make your errors more specific, like:
module.exports.loadCompany = (company, callback)=>{
MongoClient.connect(conexionString, (err, database) => {
if (err) {
callback(new Error('Connection error: ' + err.Error());
return;
}
db = database;
console.log(company);
db.collection('companies').insert(company, (err, result)=>{
if (err) {
callback(new Error('Insertion error: ' + err.Error());
return;
}
callback(null, {message:"Succesfully loaded company", company:result});
});
})
Here is your loadCompany done in async / await format.
Notise there is no need for error checking, errors will propagate as expected up the promise chain.
Note I've also changed loadCompany to be an async function too, so to call it you can simply do var ret = await loadCompany(conpanyInfo)
module.exports.loadCompany = async (company)=>{
let db = await MongoClient.connect(conexionString);
console.log(company);
let result = await db.collection('companies').insert(company);
return {message:"Succesfully loaded company", company:result};
}
I am using Meteor.JS and pcel:mysql to fetch the mysql result from the method and passing it to the helper.
In my Method, the method is getting executed fine and using connection.query I am able to log the mysql rows in the server side console.
This is what my code looks like:
if (Meteor.isClient) {
Meteor.call('mysqltestcall1', function(error, result){
Session.set('myMethodResult', result);
});
Template.hello.helpers({
data2: function(){
return Session.get('myMethodResult');
}
});
}
if (Meteor.isServer) {
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'leaderboard'
});
connection.connect();
Meteor.methods({
'mysqltestcall1': function(){
var returnresult = 'test value';
connection.query('SELECT * FROM players', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
returnresult = rows;
});
return returnresult;
}
});
}
I am getting the value as "test value", but not rows JSON data. Can anyone help me out.
I thing I am not using the variable correctly is in the nested function.
Looks like connection.query is asynchronous, therefore it has not the time to be executed and the default "returnresult" is instantly returned.
What if you move the return statement in the query callback?
connection.query('SELECT * FROM players', function(err, rows, fields) {
if (err) throw err;
console.log(rows);
return rows;
});