简体   繁体   中英

Node.js mySQL unable to create a connection

I am just starting so i know not much about both of the above. the code:

var mysql = require("mysql");
var express = require('express');
var app = express();


// First you need to create a connection to the db
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: ''
});

con.connect(function(err){
 if(err){
  console.log('Error connecting to Db');
  console.log(err);
   return;
}
console.log('Connection established');
});

con.end(function(err) {
// The connection is terminated gracefully

tried to run it with node.js but it says:

 Error connecting to Db
{ Error: connect ECONNREFUSED 127.0.0.1:3306
    at Object.exports._errnoException (util.js:1018:11)
    at exports._exceptionWithHostPort (util.js:1041:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
--------------------
    at Protocol._enqueue (C:\Users\yeohc\Desktop\Newfolder\node_modules\mysql\lib\protocol\Protocol.js:141:48)
   at Protocol.handshake (C:\Users\yeohc\Desktop\Newfolder\node_modules\mysql\lib\protocol\Protocol.js:52:41)
    at Connection.connect     (C:\Users\yeohc\Desktop\Newfolder\node_modules\mysql\lib\Connection.js:130:18)
    at Object.<anonymous> (C:\Users\yeohc\Desktop\Newfolder\app.js:13:5)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 3306,
 fatal: true }

Please help me out and keep in mind that I am just starting on the programming stuff. Thanks in before for the help

I am able to connect with your code in my machine.

In your scenario check the following cases

1- Make sure your mysql server is up on port .

2- Check the password is required?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM