I'm using the connection pool in this way:
var pool = mysql.createPool({
host: config.db.host,
port: config.db.port,
user: config.db.user,
password: config.db.password,
database: config.db.database,
connectionLimit: config.db.connectionLimit
});
exports.api_point = function(req, res) {
pool.getConnection(function(err, connection) {
if (err) {
console.error('error acquiring connection', err);
var result = {};
result.error = err.code;
res.json(result);
return;
} else {
var query = connection.query('SELECT * FROM tableName', function(err, rows) {
connection.release();
var result = {};
if (err) {
console.error('error executing query: ' + err.stack);
result.error = err.message;
} else {
result.data = rows;
}
res.json(result);
return;
});
}
});
};
Problem:
Yet, after all the connections (defined by connectionLimit, e.g. 20) are created, the next call to pool.getConnection() hangs until Express returns: "GET /api_point - - ms - -" (after ~10s).
I've tried replacing connection.release(); with connection.destroy(); with no effect.
How can I solve this?
node-mysql version:
"mysql": "~2.5.1",
Btw. I track connections being created with:
var connCount = 0;
pool.on('connection', function(connection) {
console.log('connCount:', ++connCount);
});
Whatever I changed, nothing seemed to work until I switched to using "express-myconnection" as middleware (as described here: http://teknosains.com/i/simple-crud-nodejs-mysql).
In short: you get the connection from the request and no need to release it afterwards as the middleware cares about that.
So, my code is now (only important parts):
app.js:
var myconnection = require('express-myconnection');
var mysql = require('mysql');
app.use(
myconnection(mysql, {
host: config.db.host,
port: config.db.port,
user: config.db.user,
password: config.db.password,
database: config.db.database,
connectionLimit: config.db.connectionLimit
}, 'request')
);
api.js:
exports.api_point = function(req, res) {
req.getConnection(function(err, connection) {
if (err) {
console.error('error acquiring connection', err);
var result = {};
result.error = err.code;
res.json(result);
return;
} else {
var query = connection.query('SELECT * FROM tableName', function(err, rows) {
var result = {};
if (err) {
console.error('error executing query: ' + err.stack);
result.error = err.message;
} else {
result.data = rows;
}
res.json(result);
return;
});
}
});
};
Related
The following code connected to Redshift database but returning an empty response even the response will be displayed in the console.log, why?
index.js
const config = {
user: 'user',
database: 'database',
password: 'password',
port: port,
host: 'hostname',
};
var response = [];
console.log('Before Connection');
exports.handler = function index(event, context, callback) {
var redshiftClient = new Redshift(config, {rawConnection:true});
redshiftClient.connect(function(err){
console.log('After Connection');
if(err) throw err;
else{
redshiftClient.query('SELECT * FROM customer', {raw: true}, function(err, data){
if(err) throw err;
else{
response = data;
console.log(data);
redshiftClient.close();
return response;
}
});
}
});
return response;
};
I have used the promise concept and it does returning the response properly for me.
Sample JSON {"user_id": "1001"}
var Redshift = require('node-redshift');
const config = {
user: 'user',
database: 'database',
password: 'password',
port: port,
host: 'hostname',
};
// The values passed in to the options object will be the difference between a connection pool and raw connection
var redshiftClient = new Redshift(config, {rawConnection:true});
exports.handler = async (event) => {
return new Promise(function(resolve, reject){
redshiftClient.connect(function(err){
if(err) throw err;
else{
redshiftClient.parameterizedQuery('SELECT * FROM customer where user_id = $1', [event.user_id], {raw: true}, function(err, data){
if(err) throw reject(err);
else{
resolve(data);
redshiftClient.close();
}
});
}
});
});
};
Command Shot
Above I have a screen shot of my app.js server and for some reason the connection is not going through below I have my app.js code
const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyparser = require('body-parser');
app.use(bodyparser.json());
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Adil#123',
database: 'movies'
});
mysqlConnection.connect(err=>{
if (err) {
console.log('It was not successful \n Error:' + JSON.stringify(err,undefined,2));
} else {
console.log('Its a success');
}
});
// Collecting all the movies from the movielist
app.get('/movielist',(req,res)=> {
mysqlConnection.query("SELECT * FROM movielist", (err, rows,fields)=> {
if (!err) {
res.send(rows);
} else {
console.log(err);
}
});
});
// Finding a movie based on the `idmovielist` number
app.get('/movielist',(req,res) => {
mysqlConnection.query("SELECT * FROM movielist WHERE idmovielist = ?",[req.params.id],(err, rows,fields) =>{
if (!err) {
res.send(rows);
} else {
console.log(err);
}
});
});
// Delting a movie
app.delete('/movielist/:id',(req,res) => {
mysqlConnection.query("DELETE FROM movielist WHERE idmovielist = ?",[req.params.id],(err,rows,fields) =>{
if (!err) {
res.send("Movie is deleted");
} else {
console.log(err);
}
});
});
// Inserting a movie
app.post('/movielist/addMovie',(req, res) => {
mysqlConnection.query("INSERT INTO movielist (`idmovielist`,`name`,`thumnail_path`,`description`,`language_released`,`year_released`) VALUES ('"+req.body.idmovielist+"', '"+req.body.name+"','"+req.body.thumnail_path+"', '"+req.body.description+"', '"+req.body.year_released+"', '"+req.body.language_released+"' )",
(err,rows) => {
if (!err) {
res.send("Movie is added");
} else {
console.log(err);
}
});
});
// Updating the movie list
app.put('/movielist/:id',(req,res) =>{
let update = req.body;
mysqlConnection.query("UPDATE movielist SET `year_released` WHERE = '"+update.idmovielist+"','"+update.year_released+"'",
(err, results) => {
if (!err) {
res.send("Movie list is updated");
} else {
console.log(err);
}
});
});
// localhost:3000
app.listen(3000,() => {
console.log('We got it running');
});
module.exports = app;
Above is my app.js the server was working earlier but for some reason it is not working anymore what can be the issue Is it something wrong with my code or should I change the port or create another server
I am getting error Invalid object name dbo.tbl_user.while running a query on the Azure database from a nodejs app.My code which runs is following.
const pool = new sql.ConnectionPool(DatabaseConfig.config);
pool.connect().then(function () {
//6.
debugger;
var request = new sql.Request(pool);
//7.
request.query("select * from [dbo].[tbl_user]").then(function (recordSet) {
debugger;
console.log(recordSet);
sql.close();
}).catch(function (err) {
//8.
debugger;
console.log(err);
sql.close();
});
}).catch(function (err) {
//9.
debugger;
console.log(err);
});
My connection string is :
config: {
server: 'azureserver',
options: {
database: 'cccc',
encrypt: true,
port: 1433
},
user: 'ccc',
password: 'ccccc'
}
what is the mistake I am doing here? Thanks in advance for the help.
I tested your code on my side but did not reproduce your issue.
Here is my test code:
const sql = require('mssql')
const config = {
server: '***.database.windows.net',
database: '***',
user: '***',
password: '***',
options: {
database: '***',
encrypt: true,
port: 1433
}
}
const pool = new sql.ConnectionPool(config);
pool.connect().then(function () {
//6.
debugger;
var request = new sql.Request(pool);
//7.
request.query("select * from [dbo].[Student]").then(function (recordSet) {
debugger;
console.log(recordSet);
sql.close();
}).catch(function (err) {
//8.
debugger;
console.log(err);
sql.close();
});
}).catch(function (err) {
//9.
debugger;
console.log(err);
});
Query result on the portal:
Run query.js :
You need to make sure the table name is correct, it's not related to spelling case.
Hope it helps you.
I want to call a stored procedure / function in postgresql from node/express. I am using Angular 5.
Installed packages:
express: 4.16.2,
pg: ^7.4.0
Other required packages are also installed
Below is the code of my API - I want to replace all queries with my stored procedure / function call
const express = require('express');
const router=express.Router();
const {Pool,Client} = require('pg');
const connectionString = 'postgresql://postgres:1#localhost:5432/dbAngular'
// const client = new Client({
// connectionString:connectionString
// })
router.get('/employees', (err, res, done) => {
const client = new Pool({
connectionString:connectionString
})
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established message as follow '+err.message+'')
}
});
client.query('select * from getEmployees();', (err, result) => {
if (err) {
console.log(err.stack) ;
client.end();
} else {
client.end();
console.log(result.rows);
res.json(result.rows);
}
})
})
//SAVE
router.post('/employees', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
})
console.log( req.body);
var employee=req.body;
const query = {
text: 'INSERT INTO employes(name) VALUES($1)',
values: [employee.name]
}
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established '+err.message+'')
}
});
client.query(query, (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
})
});
//delete
router.delete('/employees/:id', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
});
console.log('id passed is ' + req.param.id);
client.query('DELETE FROM employes WHERE empid=($1)',[req.param.id], (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
});
});
module.exports=router;
I'm using nodeJs express 3 framework with postgreSQL, I'm using the script below to look for a username in DB and populate a variable so I can pass it to my view.
Here is my script :
app.js
var app = express();
app.use(express.bodyParser());
......
function fncCheckUsernameAvailability(vstrUsername){
var pg = require("pg");
var client = new pg.Client({user: 'xxx', password: 'xxxx', database: 'xxx', host: 'example.com'});
var response = "";
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query("SELECT username FROM users WHERE username ='"+vstrUsername+"'", function(err, result) {
if(err) {
return console.error('error running query', err);
}
if(result.rows[0] == undefined){
//console.log("Username available");
response = "Username available";//Populating The variable here
}else{
//console.log("Username already taken");
response = "Username already taken";//Populating The variable here
}
client.end();
});
});
return response;
}
app.post("/Signup", function(req, res){
var username = req.body.username;
var Response = fncCheckUsernameAvailability(username);
console.log(Response);
}
The response variable is allways "undefined", so how can I make that script waiting until the DB checking is done to populate the "response" variable?
You cannot place return values into asynchronous functions. You would instead need to use a callback, and this is what your code might look like:
function fncCheckUsernameAvailability(vstrUsername, callback) {
client.connect(function(err) {
if (err) {
callback(err, null);
return;
}
client.query("SELECT username FROM users WHERE username ='" + vstrUsername + "'", function (err, result) {
client.end();
if (err) {
callback(err, null);
return;
}
if (result.rows[0] == undefined) callback(null, 'Username available.');
else callback(null, 'Username taken.');
});
});
};
You would use the function like this:
app.post("/Signup", function(req, res) {
var username = req.body.username;
fncCheckUsernameAvailability(username, function(err, result) {
console.log(result);
});
});