Anything wrong with how I'm using node-mysql's pool.getConnection? - mysql

node-mysql's pool.getConnection looks like this when used:
pool.getConnection(function(err, callback) {
callback(err, connection);
});
when used with exports.getConnection you type out:
var db = require('mysql');
var id = req.params.id;
db.getConnection(function(err, connection){
if(err) throw err;
connection.query('SELECT * FROM users WHERE id = ?', [id], function(err, data) {
connection.release();
if (err) throw err;
res.send(data);
});
});
I decided to abstract this out and in the mysql file I added:
exports.select = function(select, inserts, callback) {
pool.getConnection(function(err, connection) {
if (err) callback(err);
connection.query(select, inserts, function(err, response){
connection.release();
callback(err, response);
});
}
}
this way when I want to do a query I type:
db.select('SELECT * FROM users WHERE uid = ?', [id], function(err, data) {
if (err) throw err;
res.send(data);
});
I've tested this with and without inserts and with different queries. What I'm wondering is if there is anything dangerously wrong with it that I'm missing.

After Andrey Sidorov's comment I'm marking this as answered, not only because this is ok but it's not even necessary as the functionality is already built in. Thanks.

Related

I can't call query after a while in a React Native project that uses MySQL

In my project, I access the MySQL database. I can call and run queries in this database through the program. However, after a while, the called queries become dysfunctional or not called at all.
The example run of the queries:
When I investigated my problem, I found a solution that I needed to increase the maximum number of connections. However, even if I used it, there was no change.
I tried this code: SET GLOBAL max_connections = 150; from this source.
The connection part via node.js:
const connection = mysql.createPool({
host : '192.168.1.101',
user : 'db_manager',
password : '...',
database : 'venue_recommendation'
});
const app = express();
app.get('/venues', function (req, res) {
let sQuery = "SELECT * FROM mekanlar WHERE mekanlar.mahalle_no=\""+req.query.neig+"\" AND mekanlar.puan >="+req.query.star+" AND mekanlar.fiyat <="+req.query.price+";"
console.log(">>>>>",sQuery)
connection.getConnection(function (err, connection) {
if(err) throw err;
connection.query(sQuery, function (error, results, fields) {
if (error) throw error;
res.send(results);
});
});
});
app.get('/Cuisines', function (req, res) {
let sQuery = "SELECT * FROM mutfaklar;"
console.log(">>>>>",sQuery)
connection.getConnection(function (err, connection) {
if(err) throw err;
connection.query(sQuery, function (error, results, fields) {
if (error) throw error;
res.send(results);
});
});
});

Do not wait for mysql database result in node js

I tried to get result using mysql database query from called function but do not wait for result in called function. Following is my code for users.js file. I got result in getBankDetail function but do not get result in users function.
var db = require("../db/mysqlconnection");
function users(app){
app.get("/users",async function(req, res, next){
let bankDetail = await getBankDetail();
console.log("bankDetail",bankDetail); //Here I do not got result
return res.send(bankDetail);
});
}
async function getBankDetail(){
db.getConnection(async function(err, connection) {
if (err) throw err; // not connected!
await connection.query('SELECT * FROM bank', function (error, results, fields) {
connection.release();
if (error) throw error;
console.log("bank result",results); //Here I got result
return results;
});
});
}
module.exports = users;
My Question is why do not wait for result in called function? I also used async/await functionality.
function getBankDetail(){
return new Promise((resolve, reject) => {
db.getConnection(function(err, connection) {
if (err) reject(err); // not connected!
connection.query('SELECT * FROM bank', function (error, results, fields) {
connection.release();
if (error) reject(err);
console.log("bank result",results); //Here I got result
resolve(results);
});
});
});
}
And then you can use let bankDetail = await getBankDetail();
If you want to use await on your db.getConnection and connection.query you will have to use mysql2/promises library or promisify those functions yourself
Here is the implementation when you use the promisified version of your database driver:
async function getBankDetail(){
const connection = await db.getConnection();
const data = await connection.query('SELECT * FROM bank');
connection.release();
console.log("bank result", data[0]); //Here I got result
return data[0];
}

Query not working using node.js node-mysql

Whats wrong with my query? im having this error:
con.query(
'SELECT nick FROM channels WHERE room=1room',
function(err, rows) {
if (err) throw err;
console.log(rows);
}
);
I tried this, and i have the same error:
var room = "1room";
con.query(
'SELECT nick FROM channels WHERE room=' + room,
function(err, rows) {
if (err) throw err;
console.log(rows);
}
);
It is treating 1room as a variable, not a string. Wrap it in quotes and it should work.
con.query(
'SELECT nick FROM channels WHERE room="1room"',
function(err, rows) {
if (err) throw err;
console.log(rows);
}
);
For your second example, you should get in the habit of escaping the variables you use in queries for security reasons (to prevent SQL injection).
var room = "1room";
con.query(
'SELECT nick FROM channels WHERE room=?',
[room],
function(err, rows) {
if (err) throw err;
console.log(rows);
}
);

Use node-mysql to execute additional queries from each result

I'm trying to get a node-mysql connection query to work in series with the result of the original query. After all the setup is done, this is the problematic part. It seems that the connection has already ended. How can I ensure that the query in processRow gets executed in tandem with the result of the original?
function processRow(row, callback){
connection.query('INSERT INTO other_table VALUES (?)', row.id, function(err, rows, fields) {
if (err) throw err;
});
callback();
}
var query = connection.query('SELECT id from tbl limit 2');
query
.on('error', function(err){
throw err;
})
.on('fields', function(fields){
})
.on('result', function(row){
processRow(row, function(){
connection.resume();
});
})
.on('end', function(){
//
});
connection.end();
https://github.com/felixge/node-mysql
function processRow(row, callback){
connection.query('INSERT INTO other_table VALUES (?)', row.id, function(err, rows, fields) {
if (err) throw err;
callback();//callback should go here
});
}
then you could end the connection:
query.on('result', function(row){
processRow(row, function(){
connection.end(); //maybe end the connection once insertion into the table is done
});
})
I think the issue with your code that you have to call connection.pause() before calling processRow()

Nodejs with Mysql Database Return value

I have the following code. I am relative new to nodejs &js
I want to get values in 1. log but i get undefined.
Only 2. log is outputed to the log.
I read nodeJS return value from callback and
https://github.com/felixge/node-mysql but there is no example about return value.
I donot know how to use return statement with the given example in node-mysql page.
exports.location_internal = function (req, res) {
var r = getExternalLocation(2);
// 1. log
console.log(r);
res.send( r);
}
var getExternalLocation = function (id) {
pool.getConnection(function(err, connection){
if(err) throw err;
var response = {};
connection.query( "select * from external_geo_units where geo_unit_id = "+id, function(err, rows){
if(err) throw err;
response.data= rows;
// 2. log
console.log(response);
return response;
});
connection.release();
});
};
It's asynchronous, so you have to pass in a callback to get the value when it's ready. Example:
exports.location_internal = function(req, res, next) {
getExternalLocation(2, function(err, rows) {
if (err)
return next(err);
console.log(rows);
res.send(rows);
});
};
function getExternalLocation(id, cb) {
pool.getConnection(function(err, conn) {
if (err)
return cb(err);
conn.query("select * from external_geo_units where geo_unit_id = ?",
[id],
function(err, rows) {
conn.release();
cb(err, rows);
});
});
}