I'm trying to connect my database with node js but it is giving me this error . here is my code
//to connect to sql
var mysql=require('mysql');
var conn=mysql.createConnection({
host:"localhost",
user:"root",
password:"",
database:"bns"
});
conn.connect(function (err) {
if (err) {
console.log(err);
return;
}
console.log("connected");
conn.query("SELECT * FROM employee", function (err, recordset) {
if (err) {
console.log(err);
}
else {
console.log(recordset);
}
conn.close();
});
});
and I'm getting this error
Error: connect ECONNREFUSED ::1:3306 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16) -------------------- at Protocol._enqueue (C:\Users\DELL\OneDrive\Desktop\node-demo\node_modules\mysql\lib\protocol\Protocol.js:144:48) at Protocol.handshake (C:\Users\DELL\OneDrive\Desktop\node-demo\node_modules\mysql\lib\protocol\Protocol.js:51:23) at Connection.connect (C:\Users\DELL\OneDrive\Desktop\node-demo\node_modules\mysql\lib\Connection.js:116:18) at Object. (C:\Users\DELL\OneDrive\Desktop\node-demo\other.js:11:6) at Module._compile (node:internal/modules/cjs/loader:1097:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10) at Module.load (node:internal/modules/cjs/loader:975:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47 { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 3306, fatal: true } [nodemon] clean exit - waiting for changes before restart
I've had an exactly same issue.
var conn=mysql.createConnection({
host:"127.0.0.1",
user:"root",
password:"",
database:"bns"
});
try this code. I think it will work.
Now only problem i hav is why it works.. lol
You should specify the port number by which the server has to establish a connection. In your case, you had missed the port number. The code below must eliminate the problem.
var conn=mysql.createConnection({
host:"localhost",
user:"root",
password:"",
port: 3306,
database:"bns"
});