where am I closing the connection in node-mysql? - mysql

Here is my code:
var set = {
FIRST_NAME: professor.value_20,
SURNAME: professor.value_21
}
//logs
//console.log(set);
//executes query
connection.query({
sql: 'SELECT TEACHERID FROM TEACHER WHERE FIRST_NAME = ? AND SURNAME = ?',
//'INSERT INTO TEACHER set ? ON DUPLICATE KEY UPDATE FIRST_NAME = ?, SURNAME = ?',
values: [set.FIRST_NAME,set.SURNAME]
}, (err, results, fields) => {
if (err) throw err;
if(results.length < 0) {
connection.query({
sql: 'INSERT INTO TEACHER set ?',
values: [set]
}, (err, results, fields) => {
if (err) throw err;
});
}
else {
connection.query({
sql: 'UPDATE TEACHER (FIRST_NAME, SURNAME) VALUES(?,?)',
values: [set.FIRST_NAME, set.SURNAME]
}, (err, results, fields) => {
if (err) throw err;
connection.end();
});
}
});
When I run this code I get the following error:
Error: Cannot enqueue Query after invoking quit.
The problem seems to occur at the level of the third query, although I did not close the connection earlier. How do I fix this?
Another question: is it better in this case to use a pool instead of a direct connection?
Thank you!

How do I fix this?
You have to either remove connection.end() or reestablish connection beforehand.
var connection = mysql.createConnection(config); //establish new connection
connection.query({
sql: 'SELECT TEACHERID FROM TEACHER WHERE FIRST_NAME = ? AND SURNAME = ?',
//'INSERT INTO TEACHER set ? ON DUPLICATE KEY UPDATE FIRST_NAME = ?, SURNAME = ?',
values: [set.FIRST_NAME, set.SURNAME]
}, (err, results, fields) => {
if (err) throw err;
if (results.length < 0) {
connection.query({
sql: 'INSERT INTO TEACHER set ?',
values: [set]
}, (err, results, fields) => {
if (err) throw err;
});
} else {
connection.query({
sql: 'UPDATE TEACHER (FIRST_NAME, SURNAME) VALUES(?,?)',
values: [set.FIRST_NAME, set.SURNAME]
}, (err, results, fields) => {
if (err) throw err;
connection.end(); //or just remove this line
});
}
});
I don't recommend the above fixes. The best solution is to use pooling connections.
pool.getConnection(function(er,connection){
if(er){
throw er;
}
connection.query({
sql: 'SELECT TEACHERID FROM TEACHER WHERE FIRST_NAME = ? AND SURNAME = ?',
//'INSERT INTO TEACHER set ? ON DUPLICATE KEY UPDATE FIRST_NAME = ?, SURNAME = ?',
values: [set.FIRST_NAME, set.SURNAME]
}, (err, results, fields) => {
if (err) throw err;
if (results.length < 0) {
connection.query({
sql: 'INSERT INTO TEACHER set ?',
values: [set]
}, (err, results, fields) => {
if (err) throw err;
});
} else {
connection.query({
sql: 'UPDATE TEACHER (FIRST_NAME, SURNAME) VALUES(?,?)',
values: [set.FIRST_NAME, set.SURNAME]
}, (err, results, fields) => {
if (err) throw err;
});
}
});
});
This approach will remove the overhead of establishing a new connection in each query.

Related

Increment a value on MYSQL with react node.js

Why does this doesn't work
const increment = 'votes + 1'
db.query("UPDATE president SET votes = ? WHERE nickname = ?",
[increment, president], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
but this code below works
db.query("UPDATE president SET votes = votes + 1 WHERE nickname = ?",
[president], (err, result) => {
if (err) {
console.log(err)
} else {
console.log(result)
}
})
I just want to do the incrementing of mysql columns with votes = ?
I wanted to do it with the votes = ? way. Does anyone know the proper syntax of incrementing a value in mysql with react node js?

Refer to another field value to affect a new one in MySQL w/Node.js

thanks for reading.
I have a table with 3 fields, one is the ID, which autoincrements and I can´t access it from my Node.js server since it's added by MySql. Another field contains a string, and the last field should be the sum of the 3 first letters of the string field, added to the id.
The thing is, when I do my query I can't just add them up because the id doesn´t exist until the query is sent to the DB.
What should I do? It'd be such an inconvenience to handle the ID autoincrement from the API.
Thanks for your time!
After you insert the row, you can get its ID and update the third column.
connection.query('INSERT INTO yourTable (name) VALUES (?)', [name], function(err, result) {
if (err) {
throw err;
}
let code = name.substr(0, 3) + result.insertId;
connection.query('UPDATE yourTable SET code = ? WHERE id = ?', [code, result.insertId], function(err) {
if (err) {
throw err;
}
});
});
However, this won't work if you're inserting multiple rows in bulk, since result.insertId is just the last row that was inserted.
You could update all the rows where the code
connection.query('INSERT INTO yourTable (name) VALUES ?', names.map(n => [n]), function(err, result) {
if (err) {
throw err;
}
connection.query('UPDATE yourTable SET code = CONCAT(SUBSTR(name, 1, 3), id) WHERE code IS NULL', function(err) {
if (err) {
throw err;
}
});
});

Mysql Error: trying to find columns in database

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

max length sql statement

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

How to insert values into Mysql.js table in Node express project

This is my use case.
First I insert data to the customer table.
Then I get the insertId for the customer.
Then I try to insert data into address table using that id.
async function createCustomer(req, res, next) {
const customer = {
type: req.body.type,
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email
};
const first_line = req.body.first_line
console.log("Customer from front-end", customer);
try {
let query1 = "INSERT INTO customer_supplier SET ?";
connection.query(query1, customer, (error, results) => {
if (error) {
console.log("Error", error);
} else {
let userId = results.insertId;
let query2 = "INSERT INTO address (id,first_line) VALUES ?";
connection.query(query2, [userId, first_line], (error, results) => {
if (error) {
console.log("error in address ==================================", error)
} else {
res.json({
results: results
})
}
})
}
});
} catch (error) {
console.log("error from", error);
res.json({
error: error
});
}
}
But when I try to insert data into the address table,
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 \'36\' at line 1',
sqlState: '42000',
index: 0,
sql: 'INSERT INTO address (id,first_line) VALUES 36' }
Before put this question on stackoverflow I tried so many variations in my insert statement and nothing works for me.
How do I achieve this?
Your sql is not written correct,you need to add () to wrap the value
let query2 = "INSERT INTO address (id,first_line) VALUES (?,?)";
Below is the grammar to use INSERT INTO
> INSERT INTO table_name (column1, column2, column3, ...)
> VALUES (value1, value2, value3, ...);
would you try this one
let query2 = "INSERT INTO address (id,first_line) VALUES ('userId', 'first_line')"
connection.query(query2, (error, results)