mySql Insert Syntax - Not Inserting What's Expected - javascript

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 ...

Related

How to find a record by unique value inside an array in MongoDB?

I want to locate a record which has the "String to match" in his "affiliates.wallets" array. But for some reason, I'm unable to do it.
I was trying something like:
db.collection.findOne({ "affiliates.wallets": {$in: "[String to match]"}, (err, data) => console.log(err, data)})
But it returns null. So, I'm asking for help.
Simplified Wallet Schema:
Wallet {
affiliates: {
wallets: [String]
}
}
P.S: I'm using findOne method because this "String to match" which I'm using to locate the record is unique and it can be located only in one record.
You don't need $in operator. You can do it like this:
db.collection.findOne({
"affiliates.wallets": "String to match",
}, (err, data) => {
console.log(err, data)
})

Node SQLite3 - crashes when running insert on specific table

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

How to insert a data into a MySQL database via a variable?

I am trying to insert values defined in javascript at the start of the program. But it does not like me trying to insert variables, instead, I should enter the raw name.
This is the error code:
Error: ER_BAD_FIELD_ERROR: Unknown column 'username' in 'field list'
I am using a SQL database and javascript to interact with it. The value has been defined with a variable beforehand.
var username = "Mark Graham"
var password = 13.00
con.connect(function(err) {
var username = "Mark Graham"
var password = 13.00
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO staff (name, hours) VALUES (username, password)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
It should insert Mark Graham into the database.
Implements a ORM, Sequelize or use
connection.query('INSERT INTO staff (name, hours) VALUES (?, ?)', [YourVar,YourSecondVar], function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
or
connection.query({
sql: 'INSERT INTO staff (name, hours) VALUES (?, ?)',
timeout: 40000, // 40s
values: [varOne,varTwo]
}, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});

pass a json result of a mysql query as a param to my ejs in Node/express

I have a query to get all my users. I have been doing res.json(rows) to display to screen until now. Now I want to pass the object obtain from the query to a ejs file and display it. If I do like my code below, the object pass is a string and I can´t iterate or obtain the fields.
What is the best way to achive what I´m trying to do?
router.get("/users", (req, res) => {
const connection = getConnection();
const newLocal = "SELECT * FROM client";
connection.query(newLocal,(err, rows, fields) => {
if (err) {
console.log("Error "+err);
res.sendStatus(500);
return;
}
// res.json(rows);
res.render("users.ejs", {users: JSON.stringify(rows)});
});
});
It's because you're turning your Array rows into a String. Remove JSON.stringify

Send DBNull.Value instead of 'null' in nodeJS MySql

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.

Categories

Resources