My nodejs code...
app.post('/src/grades-form', function(req, res){
var daa = req.body.daa;
var os = req.body.os;
var dldm = req.body.dldm;
var ptrp = req.body.ptrp;
var bhr = req.body.bhr;
var prn = req.query.prn;
var sql = "INSERT INTO grades (daa, os, dldm, ptrp, bhr) VALUES ('"+daa+"','"+ os+"','"+ dldm+"','"+ ptrp+"','"+ bhr+"') WHERE prn = ?";
connection.query(sql, [prn], function(error, results){
if(error) throw error;
res.send(`Data stored successfully !!<br>Return to dashboard.`);
});
});
Error I'm getting...
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 'WHERE prn = '1'' at line 1
How do I overcome it?
I will provide more info if this isn't sufficient... Thank you
What you could do is perform a SELECT to check if the row is present in the database, if so perform an update, otherwise insert a new row:
app.post('/src/grades-form', function (req, res) {
const { daa, os, dldm, ptrp, bhr } = req.body;
var prn = req.query.prn;
const sqlSelect = 'SELECT * FROM grades WHERE prn = ?';
connection.query(sqlSelect, [prn], (err, result) => {
if (err) throw err;
if (result.length === 0) {
// Not found, insert new value
var sqlInsert =
'INSERT INTO grades (daa, os, dldm, ptrp, bhr) VALUES (?, ?, ?, ?, ?)';
connection.query(
sqlInsert,
[daa, os, dldm, ptrp, bhr],
function (error, results) {
if (error) throw error;
res.send(
`Data inserted successfully !!<br>Return to dashboard.`
);
}
);
} else {
// Value is present, update existing one
var sqlUpdate =
'UPDATE grades SET daa = ?, os = ?, dldm = ?, ptrp = ?, bhr = ? WHERE prn = ?';
connection.query(
sqlUpdate,
[daa, os, dldm, ptrp, bhr, prn],
function (error, results) {
if (error) throw error;
res.send(
`Data updated successfully !!<br>Return to dashboard.`
);
}
);
}
});
});
The INSERT INTO statement cannot have a WHERE clause.
If you're trying to update an existing row, use:
UPDATE grades SET daa=value, os=value, etc=value WHERE prn = 1
Related
I'm using MySQL with NodeJS with asyncs and awaits. I'm trying to get the last insertid from my inserted row but keep getting errors.
Here's the async function;
function makeDb( config ) {
const connection = mysql.createConnection( config ); return {
query( sql, args ) {
return util.promisify( connection.query )
.call( connection, sql, args );
},
close() {
return util.promisify( connection.end ).call( connection );
}
};
}
And here's the code which is failing on the queries;
try {
if(tag1){
row_b = await db.query( "SELECT tagid FROM tags WHERE tagname = ?", [tag1]);
const onetagid1 = row_b[0].tagid;
console.log('onetagid1 = ' + onetagid1);
if (row_b > 0){
row_c = await db.query("
INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?" [onetagid1, audioid, onetagid1]
);
} else {
row_d = await db.query( 'INSERT IGNORE INTO tags (tagname) VALUES (?)', [tag1]);
var twotagid1 = row_d.insertId;
console.log('twotagid1 2nd = ' + twotagid1);
row_e = await db.query(
"INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?" [twotagid1, audioid, twotagid1]
);
}
res.json('json success!');
}
}
And here's the error;
onetagid1 = 30
twotagid1 2nd = 0
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 'I' at line 1
The error is twotagid1 2nd = 0 which should not be zero.
I'm not sure why this works when the other didn't. But I'll post it here hoping someone will be able to spot it;
try {
if(tag1){
row_c = await db.query( "SELECT tagid FROM tags WHERE tagname = ?", [tag1]);
if (row_c.length > 0){
console.log('tag exists in database ');
const tagid1 = row_c[0].tagid;
console.log('tagid1 = ' + tagid1);
row_f = await db.query(
"INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?", [tagid1, audioid, tagid1 ]);
} else {
console.log('tag does not exist in database ');
row_d = await db.query( 'INSERT IGNORE INTO tags (tagname) VALUES (?)', [tag1]);
const tagInsertId = row_d.insertId;
console.log('tagInsertId = ' + tagInsertId);
row_e = db.query(
'INSERT INTO entitytag (tagid1, audioid) VALUES (?,?)
ON DUPLICATE KEY UPDATE tagid1 = ?', [tagInsertId, audioid, tagInsertId ]);
}
}
console.log('success!');
res.json(tag1);
}
I'm trying to get a variable out of a query as shown below, thanks in advance
var deutsch_meund_note = "";
connection.query(
'SELECT count(*) as sum FROM noten WHERE id = ? and fach = ?',
[id, "mathe"],
function(error, results, fields) {
if (error) {
console.log("no deutsch_schr for id: "+ id);
} else {
const deutsch_meund_viel = results[0].sum;
connection.query(
'SELECT SUM(note) as sum FROM noten WHERE id = ? and fach = ?',
[id, "deutsch_meund"],
function(error, results, fields) {
const deutsch_meund_insge = results[0].sum;
const deutsch_meund_note = deutsch_meund_insge / deutsch_meund_viel;
//this variable: **var deutsch_meund_note = deutsch_meund_note;**
});
}
});
I need to get the variable out of the "connection.query" function but when I try it like the example above it just says "undefined"
This is my insert query and now I want it to modify it using UPSERT method to check whether the reocord is existing then update if not existing insert.Here is my insert part.
jsonObj = JSON.parse(jsonData);
if (jsonObj.hasOwnProperty("PE")) {
msgId = parseInt(jsonObj["PE"]);
if (msgId == XEPT_EVENT_ID) {
var pe = jsonObj["PE"];
var uid = jsonObj["UID"];
var mac = jsonObj["MAC"];
var time = jsonObj["TIM"];
var records = jsonObj["Record"];
var digital_input = [];
records.forEach(rec => {
digital_input.push(rec[3]);
});
if (typeof con !== 'undefined' && con) {
con.connect();
var sql = "INSERT INTO sierra_ips.iot_output_log (device_code, device_id, last_updated_time, digital_input_0, digital_input_1, digital_input_2, digital_input_3, digital_input_4, digital_input_5, digital_input_6, digital_input_7)VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
con.query(sql, [uid, mac, time, digital_input[0], digital_input[1], digital_input[2], digital_input[3], digital_input[4], digital_input[5], digital_input[6], digital_input[7]],
function (err, result) {
if (err) throw err;
console.log("Record inserted");
}
);
}
}
}
I got answer using this way,
var mysql = require('mysql');
const upsert = require('mysql-upsert');
const table = 'table name'
const data = [
{ col_name: 'value' }]#your data with columns
var con = mysql.createConnection({
host: "",
user: "",
password: "b",
database: ""#config db connection
});
const { affectedRows } = upsert(con)(table, data)
con.end()
Here is reference link = [https://www.npmjs.com/package/mysql-upsert][1]
i have a node js app where i connect to mysql database via express.
Now i am trying to lock a table, calling a function and unlock these tables.
when i print the string everything works fine but when i call it in connection.query(sqlStatement) the string somehow gets sliced?
here is the node js function:
exports.participateTournament = function(req, res){
const {pid, tid} = req.body;
let sqlStatement = `lock Tables Tournament_Participant WRITE, Tournament_Approved READ;
select participate_Tournament('${pid}', '${tid}') as 'result';
unlock tables;`;
console.log(sqlStatement);
connection.query(sqlStatement, function(error, rows){
if(error){
console.log(error.message);
return res.status(400).send();
} else {
return res.status(200).send(rows[0].result);
}
})
};
when i print out the string this is the output
lock Tables Tournament_Participant WRITE, Tournament_Approved READ;
select participate_Tournament('0780b926a41bd17877894771841e6179', 'a9f0e61a137d86aa9db53465e0801612') as 'result';
unlock tables;
but i get this error message from mysql:
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 'select participate_Tournament('0780
b926a41bd17877894771841e6179', 'a9f0e61a137d8' at line 2
Here is the participate_Tournament Function:
I need to check if the max limit of participants of a tournament is reached
create function participate_Tournament(
pidP varchar(64),
tidP varchar(64)
)
returns smallint
BEGIN
declare par_amount int;
declare max_amount int;
select count(TID) into par_amount from Tournament_Participant where TID = tidP;
select max_participants into max_amount from Tournament_Approved where TID = tidP;
if(par_amount < max_amount) then
insert into Tournament_Participant(TID,PID) values(tidP, pidP);
return 1; #true
end if;
return 0;
end;
```
Thanks in Advance.
I have solved it like this now, does work for me
const {pid, tid} = req.body;
let tmpResult;
connection.beginTransaction(function(err){
if(err){
res.status(400).send();
return;
}
sqlStatement = `lock Tables Tournament_Participant WRITE, Tournament_Approved READ;`;
connection.query(sqlStatement, function(err, rows){
if(err){
console.log(err);
res.status(400).send();
}else{
sqlStatement = `select participate_Tournament('${pid}', '${tid}') as 'result';`;
connection.query(sqlStatement, function(err, rows){
if(err){
console.log(err);
res.status(400).send();
}else{
tmpResult = rows[0].result;
sqlStatement = `unlock tables;`;
connection.query(sqlStatement, function(err, rows){
if(err){
console.log(err);
res.status(400).send();
}else{
connection.commit(function(err){
if(err){
connection.rollback(function(){
res.status(400).send();
});
}else{
res.status(200).send(tmpResult.toString());
}
})
}
})
}
})
}
})
})
};
I'm using node with Mysql and here's my problem.
I'm trying to add new photos on my database and return it as an array
here is my function :
function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = []
_.each(files, function (one) {
var data = [
one.path,
_id,
0
]
var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
db.connection.query(sql, data, function (err, result) {
if (err)
deferred.reject(err.name + ': ' + err.message);
var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
if (result){
db.connection.query(sql, [result.insertId], function(err, photo) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (photo) {
new_photos.push(photo[0]);
}
});
}
})
})
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise}
The Insert works well but i can't retrieve the results to send them back to the client. (my array is empty)
Thanks.
Always promisify at the lowest level, in this case db.connection.query().
if(!db.connection.queryAsync) {
db.connection.queryAsync = function(sql, data) {
return Q.Promise(function(resolve, reject) { // or possibly Q.promise (with lower case p), depending on version
db.connection.query(sql, data, function(err, result) {
if(err) {
reject(err);
} else {
resolve(result);
}
});
});
};
}
Now the higher level code becomes very simple :
function addNewPhotos(_id, files) {
var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
return Q.all(files.map(function(one) {
return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
return db.connection.queryAsync(sql_2, [result.insertId]);
});
}));
};
To prevent a single failure scuppering the whole thing, you might choose to catch individual errors and inject some kind of default ;
function addNewPhotos(_id, files) {
var sql_1 = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)',
sql_2 = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?',
defaultPhoto = /* whatever you want as a default string/object in case of error */;
return Q.all(files.map(function(one) {
return db.connection.queryAsync(sql_1, [one.path, _id, 0]).then(function(result) {
return db.connection.queryAsync(sql_2, [result.insertId]);
}).catch(function() {
return defaultPhoto;
});
}));
};
Do the return in your async loop function when all has been done
function addNewPhotos(_id, files) {
var deferred = Q.defer();
var new_photos = [];
var todo = files.length;
var done = 0;
_.each(files, function (one) {
var data = [
one.path,
_id,
0
]
var sql = 'INSERT INTO photos(photo_link, id_user, isProfil) VALUES (?, ?, ?)';
db.connection.query(sql, data, function (err, result) {
if (err)
deferred.reject(err.name + ': ' + err.message);
var sql = 'SELECT id_user, photo_link, isProfil FROM `photos` WHERE id = ?';
if (result){
db.connection.query(sql, [result.insertId], function(err, photo) {
if (err) deferred.reject(err.name + ': ' + err.message);
if (photo) {
new_photos.push(photo[0]);
}
if(++done >= todo){
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise
}
});
}
else
{
if(++done >= todo){
deferred.resolve(Array.prototype.slice.call(new_photos));
return deferred.promise;
}
}
})
})
}