0

Trying to connect to a SQL database using javascript but I keep getting this error:

Database connection failed: Error: connect ETIMEDOUT
    at Connection._handleConnectTimeout (/Users/------/PhpstormProjects/------/node_modules/mysql/lib/Connection.js:409:13)
    at Object.onceWrapper (events.js:421:28)
    at Socket.emit (events.js:315:20)
    at Socket._onTimeout (net.js:480:8)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7)

Have scoured the web but cannot find any solution. What am I doing wrong? Here is my code:

var mysql = require('mysql');

var connection = mysql.createConnection({
    host     : "----.---------.-------.amazonaws.com",
    user     : "--------",
    password : "--------"
});

connection.connect(function(err) {

    connection.end();

    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }

    console.log('Connected to database.');
});

  • 1
    It looks like similar with [etimedout-error-when-querying-mysql-database](https://stackoverflow.com/questions/40868653/etimedout-error-when-querying-mysql-database) question. Test with switch position `connection.end();` in `connect(function(err) { /* here */ })` – Zem Apr 08 '21 at 00:04
  • Doesn’t help... still same error – Marshall Scudder Apr 08 '21 at 02:42
  • @jain did I move it to the right place? – Marshall Scudder Apr 08 '21 at 19:43
  • Basically yes, but replace `connection.end()` under `console.log('Connected to database.')` is better. `connection.connect(function(err){ if(err) {console.log('err'); return;} console.log('Connected to database.'); connection.end(); });` is what i want to tell. – Zem Apr 12 '21 at 01:44
  • I tried connection.end() at multiple places and it didn't help – Marshall Scudder Apr 12 '21 at 01:49
  • I don't know more about why upper code error. Sorry to that. When you upload code for first, `connection.end()` can cause similar error because of position (`.connect()` function run asynchronous, `connection.end()` could be run first before connected) – Zem Apr 12 '21 at 02:01

1 Answers1

0

This one I actually found out myself. I was using phpstorm as an IDE and trying to connect to sql through my app.js file. I also use an aws ec2 instance to connect to my database which had already established a connection previously. I used SSH to connect to my ec2 instance, then created an app.js in my /var/www/html folder and connected from there without a problem.