I have a node mysql connection that used to work properly but since traffic started coming i am getting a strange error
Error: Connection lost: The server closed the connection.
This is the class that i'm using
const mysql = require('mysql');
class Database {
constructor() {
this.connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 3306,
debug: false,
multipleStatements: false
});
}
query(sql, args) {
return new Promise((resolve, reject) => {
this.connection.query(sql, args, (err, rows) => {
if (err)
return reject(err);
resolve(rows);
});
});
}
close() {
return new Promise((resolve, reject) => {
this.connection.end(err => {
if (err)
return reject(err);
resolve();
});
});
}
}
module.exports = Database;
Can someone help as to why this is happening?
Edit: this is how i call the code
const database = new Database();
database.query(`select * from users...
`, [req.user.id, parseInt(req.body.after)])
.then(rows => {
appData[".."] = rows['ddd']
res.status(200).json(appData);
database.close()
}, err => {
return database.close().then(() => { throw err; })
})
.catch(err => {
console.log(err);
res.status(500).json("Database Error");
})
first create file ex database.js
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: conf_core_sys.dbConfig.host,
user: conf_core_sys.dbConfig.user,
dateStrings: true,
password: conf_core_sys.dbConfig.pass,
database: conf_core_sys.dbConfig.dbName,
port:conf_core_sys.dbConfig.port,
debug: false
});
module.exports = pool;
exports.executeQuery = function (query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
throw err;
}
connection.query(query, function (err, rows) {
connection.release();
if (!err) {
callback(null, {
rows: rows
});
}
});
connection.on('error', function (err) {
throw err;
return;
});
});
}
second step :
let database = require("database")
let sql ="SELECT * from users";
database.query(sql, function (error, results, fields) {
if (error) {
callback(results)
} else {
callback(results)
}
})
some time ago i had the same problem, but at this time the probelm has not happened, maybe this solution helping you,
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit: 10,
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: 3306,
debug: false,
multipleStatements: false
});
module.exports = pool;
exports.executeQuery = function (query, callback) {
pool.getConnection(function (err, connection) {
if (err) {
connection.release();
throw err;
}
connection.query(query, function (err, rows) {
connection.release();
if (!err) {
callback(null, {
rows: rows
});
}
});
connection.on('error', function (err) {
throw err;
return;
});
});
}
Related
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);
});
});
I made this:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
console.log(query('SELECT * FROM `users`'))
and I got back
Promise { <pending> }
How do I get back my results from querying the database, just like PHP can do?
In PHP I never had to do such a thing like async/await and promises...
I also tried using mysql:
const mysql = require('mysql')
const db = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'nodejs'
})
function query(query) {
db.query(query, (err, result) => {
if (err) throw err
return result
})
}
console.log(query('SELECT * FROM `users`'))
but I got an undefined result
try this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
// function definition
function runQuery (con, sqlQuery) {
return new Promise((resolve, reject) => {
console.log("START");
if(con){
con.connect(function (err) {
if (err) throw err;
});
if (sqlQuery) {
con.query(sqlQuery, function (error, result, fields) {
connection.end(); // end connection
if (error) {
throw error;
} else {
return resolve(result);
}
});
} else {
connection.end(); // end connection
// code: handle the case
}
} else {
// code: handle the case
}
});
}
var sqlQuery = 'SELECT * FROM tableName';
// function call and pass the connection and sql query you want to execute
var p = runQuery(con, sqlQuery);
p.then((data)=>{ // promise and callback function
console.log('data :', data); // result
console.log("END");
});
I am not very familiar with MySQL and the libraries that you are using.
However, the Promise { <pending> } response that you are getting is because you didn't await your query execution.
Since the function is marked as async and is also performing an async action, it returns a Promise that needs to be awaited to be resolved.
The code below should work:
const mysql = require('mysql2/promise')
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'nodejs',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
})
async function query(query) {
const result = await pool.query(query)
return result[0]
}
(async () => {
const queryResult = await query('SELECT * FROM `users`');
console.log(queryResult);
} )();
To understand how async-await works, consider the code below:
console.log('I will get printed first');
const asyncFunction = async () => {
await setTimeout(()=> {}, 1000)
console.log('I will get printed third');
return 'hello'
}
(async () => {
const result = await asyncFunction();
console.log(`I will get printed last with result: ${result}`);
})();
console.log('I will get printed second');
The console.log statement I will get printed last with result will wait for the asyncFunction to complete execution before getting executed.
Try 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 customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Hi i want to use Mysql's beginTransactio or transactio commit rollback functionality in my Lambda(Node) function.
I tried basic structure of mysql package but seems its not working in lambda
const mysql = require('mysql');
exports.handler = async (event) => {
const con = mysql.createConnection(
{
host: "host",
user: "user",
password: "*****",
database: "db"
}
);
con.beginTransaction(
function (err) {
con.query(
"query goes here",
function (err, status) {
if (err) {
con.rollback();
con.end();
return err;
} else {
con.commit();
con.end();
return true;
}
})
});
}
sorry for the delayed answer.
just needed to specify beginTransaction without callback
const mysql = require('mysql');
exports.handler = async (event) => {
const con = mysql.createConnection(
{
host: "host",
user: "user",
password: "*****",
database: "db"
}
);
con.beginTransaction(); //here i was declaring standard callback function with err parameter
con.query(
"query goes here",
function (err, status) {
if (err) {
con.rollback();
con.end();
return err;
} else {
con.commit();
con.end();
return true;
}
});
}
I'm using socket.io in order to send message to the user when he join my site and initializing his details using cookie sent by the client. After a while and few refreshes performed my queries stop working.
Here's my code:
io.on('connection', function(socket) {
var user = false;
socket.on('hash', function(hash, gameType) {
socket.join(gameType);
query('SELECT * FROM `users` WHERE `hash` = ' + pool.escape(hash), function(err, row) {
if((err) || (!row.length)) return socket.disconnect();
user = row[0];
users[user.steamid] = {
socket: socket.id,
balance: parseInt(row[0].balance)
}
socket.emit('message', {
balance: row[0].balance,
type: 'hello',
user: row[0].steamid
});
}
}
function query(sql, callback) {
console.log(callback);
if (typeof callback === 'undefined') {
callback = function() {};
}
pool.getConnection(function(err, connection) {
if(err) return callback(err);
logger.info('DB Connection ID: '+connection.threadId);
connection.query(sql, function(err, rows) {
if(err) return callback(err);
connection.release();
return callback(null, rows);
});
});
}
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'logs/site.log' }
]
});
var logger = log4js.getLogger();
var pool = mysql.createPool({
connectionLimit : 10,
database: 'test',
host: 'localhost',
user: 'root',
password: 'pw'
});
process.on('uncaughtException', function (err) {
logger.trace('Strange error');
logger.debug(err);
});
my guess is the reason is you exhaust the connection pool.
if(err) return callback(err); << after some erros here
connection.release(); << not released if there is an error
just release the connection before this line
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');
}
});