'Getting Error while connection to MySQL from NodeJS

const mysql = require("mysql");

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: ""
});

con.connect(function (err) {
    if (err) throw err;
    console.log("Connected!");
});

I am learning NodeJS. I am trying to connect Node with Mysql Database. Above is my code and below is output I am getting when i exectue this code. Please help me with this.

Thanks in advance.

Error

Error: connect ECONNREFUSED 127.0.0.1:3306
    at TCPConnectWrap.afterConnect [as incomplete] (node:net:1157:16)

at Protocol.handshake (node_modules\mysql\lib\protocol\Protocol.js:51:23)
    at Connection.connect (node_modules\mysql\lib\Connection.js:116:18)
    at Object.<anonymous> (index.js:9:7)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 3306,
  fatal: true

cannot identify. Tried to connect with mysql from command line. It succeeded, problem is only with node



Solution 1:[1]

You have to mention database name here:

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "You_DB_Name"
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aimsat