node.js won't connect to mysql - javascript

Code:
var mysql = require('mysql');
var db_config = require('./db-config.json');
var connection = mysql.createConnection({
host: db_config.host,
user: db_config.user,
port: db_config.port,
password: db_config.password,
database: db_config.database
});
connection.connect(function(err){
if (!err) {
console.log("Database is connected... \n\n");
} else {
console.log("Error connecting database \n\n" + err);
}
});
connection.query('select 1+1 as solution', function(err, rows, fields){
if(err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
and my ./db-config.json is
{
"host": "**.*.**.***",
"user": "***",
"port": "13306",
"password": "****",
"database": "***"
}
and error is
Error connecting database
Error: Connection lost: The server closed the connection.
C:\project\Nodejs\my-app\routes\db\dbtest.js:21
if(err) throw err;
^
Error: Connection lost: The server closed the connection.
at Protocol.end (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:113:13)
at Socket.<anonymous> (C:\project\Nodejs\node_modules\mysql\lib\Connection.js:109:28)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1055:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
--------------------
at Protocol._enqueue (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:145:48)
at Protocol.handshake (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (C:\project\Nodejs\node_modules\mysql\lib\Connection.js:130:18)
at Object.<anonymous> (C:\project\Nodejs\my-app\routes\db\dbtest.js:12:12)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
This is very strange because this database is already used in another program and its works just fine.
I think the code itself is the problem because my local mysql has no problem.
I just start learning nodejs & express and at stuck at this very basic stage. Any help is appreciated.

You are ending the connection to the DB before the callbacks do their job.
var mysql = require('mysql');
var db_config = require('./db-config.json');
var connection = mysql.createConnection({
host: db_config.host,
user: db_config.user,
port: db_config.port,
password: db_config.password,
database: db_config.database
});
connection.connect(function(err){
if (err) {
console.log("Error connecting database \n\n" + err);
throw err
}
connection.query('select 1+1 as solution', function(err, rows, fields){
if(err) throw err;
console.log('The solution is: ', rows[0].solution);
connection.end();
});
});
Callbacks don't execute immediately, they are asynchronous. Your code is getting to connection.end() before it has done all the async operations.

Related

Cant access Azure SQL server from nodejs

I am trying to do a simple query to my azure SQL server from NodeJs, im getting errors that i cannot connect to the server. all the details are correct because i used them on another application i built in C#.
my code:
var mysql = require('mysql');
var config =
{
host: Server,
user: UserName,
password: PassWord,
database: Database
};
const conn = new mysql.createConnection(config);
conn.connect(
function (err) {
if (err) {
console.log("!!! Cannot connect !!! Error:");
throw err;
}
else
{
console.log("Connection established.");
queryDatabase();
}
});
function queryDatabase(){
conn.query('SELECT * FROM Drinks', function (err, results, fields)
{
if (err) throw err;
console.log(results);
})
conn.end(function (err) {
if (err) throw err;
else console.log('Done.')
});
};
I have tried making port rules, allowing nodejs through firewall, turning off firewall, I have added my IP to the firewall on the azure group and still cant connect. Any help would be awesome. Thanks!
Error:
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:211:20)
--------------------
at Protocol._enqueue (C:\node\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\node\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\node\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (C:\node\test.js:14:6)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
Ok so i worked out how to do it! and for anyone with similar issues do this.
Instead of mysql i used mssql and it worked straight away.
Example:
var sql = require('mssql');
var config = {
server: "XXX.database.windows.net",
database: "XXX",
user: "XXX",
password: "XXX",
port: 1433,
options: {
encrypt: true
}
};
sql.connect(config).then(function() {
console.log("connected")
sql.query('SELECT * FROM Drinks', function (err, results, fields)
{
if (err) throw err;
console.log(results);
})
})

Unable to connect to remote MySQL database with mysql package

I have tried to connect to my remote MySQL database server with npm's mysql package but it keeps on throwing this error
But it works fine when I use mysqli with PHP
ERROR:
Error: connect ETIMEDOUT
at PoolConnection.Connection._handleConnectTimeout (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/Connection.js:409:13)
at Object.onceWrapper (events.js:416:28)
at Socket.emit (events.js:310:20)
at Socket._onTimeout (net.js:479:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
--------------------
at Protocol._enqueue (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at PoolConnection.connect (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/Connection.js:116:18)
at Pool.getConnection (/home/rilla/Desktop/dbTest/node_modules/mysql/lib/Pool.js:48:16)
at Object.<anonymous> (/home/rilla/Desktop/dbTest/test.js:22:6)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
MY CODE:
// Get the mysql service
var mysql = require("mysql");
// Add the credentials to access your database
// var connection = mysql.createConnection({
// host: "my_host", // hosts IP here
// port: 3306,
// user: "my_username",
// password: "my_password",
// database: "my_database",
// });
var pool = mysql.createPool({
connectionLimit: 100,
host: "my_host", // hosts IP here
port: 3306,
user: "my_username",
password: "my_password",
database: "my_database",
});
pool.getConnection(function (err, conn) {
if (err) {
console.log(err);
} else {
console.log('it works now')
}
});
// connect to mysql
// connection.connect(function (err) {
// // in case of error
// if (err) {
// console.log(err);
// console.log(err.code);
// console.log(err.fatal);
// } else {
// console.log('it works now')
// }
// });
I have tried with sequelize too but no avail. I can't figure why it's not connecting

how to connect to MySQL(phphmyadmin) from Node.js?

When installing a fresh version of xampp I'm able to connect my js script to MySQL through the terminal.
const mysql = require('mysql');
let con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
port:3307
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
PS C:\login> node connection.js
Connected!
I've been trying another db which I have credentials for but it seems to be a problem when you have a password property in the con object. That it will not connect with a password :P What Im I doing wrong here?
C:\login\connection.js:13
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:16)
--------------------
at Protocol._enqueue (C:\login\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\login\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (C:\login\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (C:\login\connection.js:12:7)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11 {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"xyz"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
PS C:\login> node connection.js
Connected!

I'm getting a Error using node package mysql v2.16.0 while connecting to database Error: Packets out of order. Got: 80 Expected: 0

versions:
node > 11.4.0
mysql(node package) > 2.16.0
phpMyAdmin > 4.8.3
MySQL > 5.7
I'm using this code:
const mysql = require('mysql');
let db = mysql.createConnection({
host:'hidden',
port:'hidden',
user:'hidden',
password:'hidden',
database: 'hidden',
dubug: true
});
sqlfn.createTable('Internal', db, 'test_table', (result, err) => {
if(err) {console.log(err.stack); return};
console.log('Create OK: ', result);
});
From the function file sqlfn:
exports.createTable = (req, db, name, callback) => {
let query_string = String(`CREATE TABLE ${name} (uid VARCHAR(255), name VARCHAR(255), type VARCHAR(255), data VARCHAR(255), modified VARCHAR(255))`);
db.query(query_string, (err, result) => {
if(err) fn.logit(req, 'SQL', 'error', `in <createTable> ${err}`);
callback(result, err);
});
};
This is the error that I am getting:
>
Error: Packets out of order. Got: 80 Expected: 0
at Parser.write (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\protocol\Parser.js:42:19)
at Protocol.write (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\protocol\Protocol.js:38:16)
at Socket. (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\Connection.js:91:28)
at Socket. (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\Connection.js:502:10)
at Socket.emit (events.js:189:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:145:17)
--------------------
at Protocol._enqueue (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\protocol\Protocol.js:144:48) at Protocol.handshake (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\protocol\Protocol.js:51:23) at Connection.connect (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\Connection.js:118:18)
at Connection._implyConnect (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\Connection.js:453:10) at Connection.query (C:\Users\hidden\Documents\Git\hidden\node_modules\mysql\lib\Connection.js:198:8)
at Object.exports.createTable (C:\Users\hidden\Documents\Git\hidden\components\functions\sql.js:36:8)
at Object. (C:\Users\hidden\Documents\Git\hidden\components\controllers\controll_admin.js:22:7)
at Module._compile (internal/modules/cjs/loader.js:723:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:734:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
If anyone know how i can fix or work-around this I'd love some feedback and help regarding this.
thank you.
:)
I was getting the same error and it was because I was not setting the correct port for my database which was 3305 instead of the default 3306

error while creating database using node js

I am new to node js and i am trying to create a database.
i copied code from w3school and tried to run in my pc.
i got the following error:
C:\Users\HP\Desktop>node db.js
C:\Users\HP\Desktop\db.js:10
if (err) throw err;
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at Object._errnoException (util.js:999:13)
at _exceptionWithHostPort (util.js:1020:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1207:14)
--------------------
at Protocol._enqueue (C:\Users\HP\node_modules\mysql\lib\protocol\Protocol.j
s:145:48)
at Protocol.handshake (C:\Users\HP\node_modules\mysql\lib\protocol\Protocol.
js:52:23)
at Connection.connect (C:\Users\HP\node_modules\mysql\lib\Connection.js:130:
18)
at Object.<anonymous> (C:\Users\HP\Desktop\db.js:9:5)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
C:\Users\HP\Desktop>
db.js:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "myusername",
password: "mypassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
/*Create a database named "mydb":*/
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
I am completely new to node js.

Categories

Resources