Unable to connect MySQL DB, getting ECONNREFUSED - javascript

I tried to connect the DB via MySQL Java Script as below:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "******",
user: "******",
password: "******"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
And I'm using Node to execute, While I execute the above program getting the below error message:
if (err) throw err;
^
Error: connect ECONNREFUSED XX.XXX.XX.XXX:3306
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
Also I have pinged my ip address (ping XX.XXX.XX.XXX) and can able to get the response. Can help me to connect the DB.

I had the same issue and the error resolved by adding the socketPath parameter
var connection = mysql.createConnection({
user: 'user',
password: 'pass',
socketPath: '/var/run/mysqld/mysqld.sock',
database: 'dbname'
});

I highly suggest creating a connectionPool to save your resources. Here is how I did it:
//import settings.js
const db_config = {
hostname : "localhost",
user : settings.user, //username
password : settings.password, //password
database : settings.database //db
}
//create db connection pool
const con = mysql.createPool(db_config);
So the next step is to use that connection pool! Don't be scared about the async/bluebird nature of this code, it's just how I built it.
async function query(sql, params) {
const connection = await con.getConnectionAsync();
return connection.queryAsync(sql,params)
.then(rows => rows)
.finally(() => connection.release());
}
This is grabbing the connection getConnection method (Async is from bluebird promisifying the method), and using the query method (async'd), and then finally releasing the connection back into the pool. This helps save you from memory leaks caused by unclosed TCP connections.
Make sure that you also specify the port if you have changed it from the default MySQL port as well.

Related

How to run node postgres inside Electron?

I'm trying to use postgres (pg) inside electron.
When the window opens, the connection and query works normally, but when the electron window is reloaded, pg connect and queries does not return anything.
<script>
const { Client } = require('pg')
async function query() {
const client = new Client({
host: '192.168.99.100',
port: 5433,
user: 'user',
password: 'password',
database: 'database',
})
console.log(await client.connect())
const res = await client.query('SELECT * from users')
console.log(res)
await client.end()
}
query()
</script>
PS: If i try to use Knex for connect and query the database, it returns this error:
Uncaught (in promise) KnexTimeoutError: Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?
at Client_PG.acquireConnection

TypeError: Net.createConnection is not a function`

I'm trying to connect to a MySQL database using React and Node, and I created a database class to act as a singleton to get the connection to the database, but then it gives me the following error:
TypeError: Net.createConnection is not a function
I've done some searching and the main search results I can see are that the code is rendering client side, which doesn't completely make sense to me, considering I'm running this on node js through npm start.
let con = null;
class Database
{
}
Database.prototype.connection = function()
{
if(con!=null) {
return con;
}
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
return con;
}
export default Database;
I apologize if I don't know the correct terminology.
Error I see in the browser

Trouble making nodejs mysql connection

I am trying to make a simple connection between my nodejs server and my mysql db (using Microsoft SQL server manager studio v14), below is my code and the error message appearing in my console window.
here is my code:
var express = require('express');
var app = express();
var sql = require("mssql");
app.get('/', function (req, res) {
// config for your database
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Schools', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
The error I am getting looks like this:
Server is running..
tedious deprecated The default value for `options.encrypt` will change from `false` to `true`. Please pass `false` explicitly if you want to retain current behaviour. node_modules\mssql\lib\tedious.js:212:23
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.tedious.once.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:275:13)
at Connection.emit (events.js:182:13)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:14)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
code: 'ESOCKET',
originalError:
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\errors.js:12:12)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:30)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:174:19)
message: 'Failed to connect to localhost:1433 - Could not connect (sequence)',
code: 'ESOCKET' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1299:37)
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1242:12)
at C:\Users\smr09\Desktop\Code\ou\db_test\test.js:24:17
at _poolCreate.then.catch.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:178:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
I am rather new at this particularly with dealing with databases. Can someone explain what the error means?
Add this line to the config:
options: {
encrypt: false
}
It will finally look like:
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX' ,
options: {
encrypt: false
}
};
try to put encrypt: false in your config{}, it will work.
your error:
ConnectionError: Failed to connect to localhost:1433 - Could not
connect (sequence)
My problem was resolved by adding port
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX',
port: '',
};

acess function in objected, nested inside another function

Im trying to manage a connection instance, using a function to handle idle connection disconnect issues, using mysql database and node.js
At moment, i've got following code (coffescript):
mysql = require 'mysql'
handleDisconnect = () ->
connection = mysql.createConnection
host: 'localhost'
user: 'root'
password: 'passroot'
database: 'mydb'
connection.connect (err) ->
if err
console.log 'Error connecting to db: ', err
setTimeout handleDisconnect, 2000
connection.on 'error', (err) ->
console.log 'db error', err
if err.code == 'PROTOCOL_CONNECTION_LOST'
handleDisconnect()
else
throw err
handleDisconnect.instance = connection
module.exports = handleDisconnect
and
express = require 'express'
router = express.Router()
connection = require('../database')().instance
bcrypt = require 'bcryptjs'
router.post '/', (req, res) ->
credential = connection.escape req.body.credential
password = connection.escape req.body.password
res.send credential+password
module.exports = router
Problem is, when i try to access the route, i get following error:
Cannot read property 'escape' of undefined
What am i doing wrong?
I believe your issue is that the final line of handleDisconnect is returning the instance, so you're trying to get the instance from instance, not from handleDisconnect. So you'll need the function to return itself at the end if you want to access properties on it.
You also want the function to be using the equivalent of "this" (# in coffeescript) rather than specifically referring to handleDisconnect.
Example code:
mysql = require 'mysql'
handleDisconnect = () ->
connection = mysql.createConnection
host: 'localhost'
user: 'root'
password: 'passroot'
database: 'mydb'
connection.connect (err) ->
if err
console.log 'Error connecting to db: ', err
setTimeout handleDisconnect, 2000
connection.on 'error', (err) ->
console.log 'db error', err
if err.code == 'PROTOCOL_CONNECTION_LOST'
handleDisconnect()
else
throw err
#instance = connection
#
module.exports = handleDisconnect
Although I'd personally just do the following, don't bother with "instance" at all:
Use #connection in your function
Scrap the #instance = connection
Get the function to return itself
Access it with require('../database')().connection.

Node server Unable to connect the mysql database connect ETIMEDOUT at Connection._handleConnectTimeout

I am unable to connect the mysql database. When I trying to start node server many time it throw database connection error.
Error is :-
connect ETIMEDOUT
at Connection._handleConnectTimeout
Create a file mysql_yourname with:
const mysql = require('mysql');
const conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "pass",
database: "databaase"
});
conn.connect(function(err) {
if(err) throw "There is no connection to the mysql server..." + err.message;
console.info("Connected!");
});
exports.conn = conn;
then require that module in your code and you will be connected.
Connected!

Categories

Resources