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());
}
})
}
})
}
})
}
})
})
};
Related
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
Im trying to insert user data into my mysql database but Im getting this error " sql: 'SELECT * FROM users WHERE undefined = ?' "
Here is my code :
find: function(user = null, callback) {
//if the user variable is defined
if(user) {
var field = Number.isInteger(user) ? 'id' : 'email';
}
// prepare the sql query
let sql = `SELECT * FROM users WHERE ${field} = ?`;
pool.query(sql, user, function(err, result){
if(err) throw err;
if(result.length){
callback(result[0]);
} else {
callback(null);
}
});
},
I have i Mysql query with nodejs like this :
application.get('/Modification/:idt',function(req,res){
connection.query("SELECT * FROM memos WHERE idMemo = 'req.params.idt'",function (error, rows){
if (error) {
console.log("error ocurred",error);
}
else {
console.log(req.params.idt);
console.log(rows);
var no = rows;
res.render('memosModif.ejs', {no});
}
});
});
and my query return an empty array even if req.params.idt return an int value like 1 or 2 ... , but when i replace req.params.id with a int like 1 or 2 ... the query returns the right result
i dont understand why and how to fix that .
You are comparing the idMemo column to the string literal 'req.params.idt'. Instead, you should bind the value from this variable:
connection.query("SELECT * FROM memos WHERE idMemo = ?", req.params.idt, function (error, rows) {
Using NodeJS and MySQL I had an error in my query statement of database fields called user_name.
Why user_name makes an error and what is the solution?
function get_role(callback) {
tempCont.query('SELECT * from `users` where `user_name` = ahmed' , function (error, results) {
if (error) callback(null);
callback(results[0].password);
console.log("from query = " + results[0].password);
});
}
You have a bare keyword (ahmed) which should be quoted:
function get_role(callback) {
tempCont.query("SELECT * from `users` where `user_name` = 'ahmed'" , function (error, results) {
if (error) callback(null);
callback(results[0].password);
console.log("from query = " + results[0].password);
});
}
function get_role(callback) {
tempCont.query("SELECT * from users where user_name = 'ahmed'" , function (error, results) {
if (error) callback(null);
callback(results[0].password);
console.log("from query = " + results[0].password);
});
}
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;
}
}
})
})
}