Terminating a callback in nodejs - mysql

I am very new to nodejs. I am using mysql node module. This is how I use it:
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'sample'
});
connection.connect(function (err) {
if (!err) {
console.log("Database is connected ... \n\n");
} else {
console.log("Error connecting database ... \n\n");
}
});
var post = {PersonID: 1, Name: 'Prachi', City: 'Blore'};
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});
console.log(query.sql);
This node code works functionally. As in, it adds data to the table. But it doesn't terminate. What is the mistake which I am making?

Take a closer look at the official documentation, you have to close the connection :
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();

Use connection.end() to close the connection
var query = connection.query('INSERT INTO Persons SET ?', post, function(error, result) {
connection.end();
if (error) {
console.log(error.message);
} else {
console.log('success');
}
});

Related

How to pass multiple parameters for promise function in Nodejs connected with MYSQL server?

let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'priyanka',
password: '1234',
database: 'todoapp'
});
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
// promise function
query = `select device from user_table limit 34`;
sql = function(device){
return new Promise(function(resolve,reject)
{
connection.query(query, (error, results) => {
if (error) {
reject( console.error(error.message));
}
resolve(console.log(results));
});
})
}
sql('device').then(function(rows) {
}).catch((err) => setImmediate(() => { throw err; }));
connection.end();
sql('device') -> inside sql call , can i only place comma separated field values to get rows from user_table or is there any other way to pass multiple columns ?

Node JS Express MySQL , can not get all users

I can't get all users, but if write manually it works.
class User {
static getAll(result) {
let sql = `SELECT * FROM users`;
sql.query(sql, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("users: ", res);
result(null, res);
});
}
}
exports.findAll = (req, res) => {
User.getAll = (err, data) => {
if (err) return res.status(500).send({ message: err.message || "Some error occurred while retrieving users." });
res.send(data);
}
}
query() is a method of a mysql connection, you are using it as a string method:
let sql = 'SELECT * FROM users';
sql.query()
You should first create the connection with your database, and then use that connection object to make your queries, something like this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

Node JS App resulting in Too Many Connections on MySQL

This is how my code looks like:
var con = mysql.createPool({
connectionLimit : 10,
host: 'X.X.X.X',
user: 'abcd',
password: '1234',
database: 'basic'
});
con.query('INSERT INTO tbasic SET ?', data, (err, ret) => {
if(err) {
res.status(200).json({
response_code:500,
message:'Error inserting data!',
data:err
});
}
else {
console.log('Last insert ID:', ret);
res.status(200).json({
response_code:200,
message:'ok',
data:ret
});
}
});
Whenever this application runs, after a while I get Too many connections error on the DB.
I know about the possible duplication issue but I have tried almost all solutions I found so far. None of them seems to work. What am I missing here?
Try using the long-handed way of pooling connections
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host: 'X.X.X.X',
user: 'abcd',
password: '1234',
database: 'basic'
});
pool.getConnection(function(err, connection) {
if (err) throw err; // No connection
connection.query('INSERT INTO tbasic SET ?', function(error, ret) {
if(error) {
res.status(200).json({
response_code:500,
message:'Error inserting data!',
data:error
});
} else {
console.log('Last insert ID:', ret);
res.status(200).json({
response_code:200,
message:'ok',
data:ret
});
}
// Release current connection
connection.release();
// Handle error after connection released
if (error) throw error;
});
});

How to create a awaitable connection with mysql using node.js

I'm new with Node.js and I'm trying to create a async method with Node.js, because I need to check a row inside of my database and then decide what to do with it. So I created a file called sql-service.js
const sql = require('mysql');
var connection = sql.createConnection({
host: '0.0.0.0',
user: 'foo',
password: 'fooo'
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
console.log(connection.state);
module.exports.SignUpUser = (email,password)=>{
connection.query('select * from usuario', function(error, results, fields) {
console.log(results);
});
}
And inside of my Controller :
const sqlService = require('../services/sql-service');
exports.post = async(req,res,next)=>{
const Email = req.body.Email;
const Passw = req.body.Password;
console.log(dateT.getdate());
if (fluentValidation.validateEmail(Email) && fluentValidation.isValidLenght(Passw)) {
try {
await sqlService.SignUpUser(Email,Passw);
//emailService.send(req.body.Email,'Nome','Bem vindo ao hanggu');
} catch (error) {
console.log(error);
}
res.status(201).send({
Email: "Valid " + req.body.Email,
Password: Passw.length,
Send: 's '//Date : dateT.getDateTime()
});
} else {
res.status(500).send({
Error: "Email invalid"
})
}
}
It does connect but the result that I got it's undefined, I tried
console.log('The solution is: ', results[0].usuario);
But still.
what schema you select?
var connection = sql.createConnection ({
host: '0.0.0.0',
user:'foo',
password : 'fooo',
database : 'you_db'
});
test

nodejs mysql using data in other modules/files

I'm trying to get data from my DB and use it in different modules of my app. My app is split in a lot of modules which I require where I need them.
My connectDB.js module looks like this
var mysql = require('mysql');
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "pw",
database : "something"
});
db.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Database connected');
});
function select(query)
{
db.query(query,function(err,rows){
if(err) throw err;
return rows;
});
}
module.exports =
{
select
}
I was hoping to simply just require this module and then do a something like
db.select('SELECT * FROM users');
But for some reason the return value is always "undefined"
Sending queries inside the connectDB module works as expected returning the correct data. But I can't use my function to get data.
Is there something wrong here with my logic? Can you help what I am doing wrong?
As I remember, connection.query will return result async, so you need to wrap it with callback or Promise.
var mysql = require('mysql');
function DB {
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "pw",
database : "something"
});
db.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Database connected');
});
this.select = function(query, callback) {
db.query(query,function(err,rows){
if(err) throw err;
callback(rows);
});
}
//Promise version
this.selectPromise = function(query) {
return new Promise(function(resolve, reject){
db.query(query,function(err,rows){
if(err) reject(err);
resolve(rows);
});
});
}
}
module.exports = DB;
How to use:
var DB = require('your-module');
var db = new DB();
db.query('select * from table', function(result) {
console.log(result);
});
db.selectPromise('select * from table').then(function(result) {
console.log(result);
});
Make the following change to your code
module.exports =
{
select: select
}
And you forgot about callback function
function select(query, callback)
{
db.query(query,function(err,rows){
if(err) throw err;
return callback(rows);
});
}
Then you can pass a function like this:
db.select('SELECT * FROM users', function(rows) {
// Do stuff with rows
});