Node.js connect mysql error - mysql

I have a file con_mysql.js with the following content:
var client = require('mysql');
client.createClient({'host':'localhost','port':3306,'user':'root','password':'root'});
client.connect();
then:
# node con_mysql.js
chris:db chris$ node my.js
/Users/chris/node_modules/mysql/lib/client.js:40
throw new Error('deprecated: connect() is now done automatically.');
^
Error: deprecated: connect() is now done automatically.
at Client.connect (/Users/chris/node_modules/mysql/lib/client.js:40:9)
at Object.<anonymous> (/Users/chris/jswork/nodejs/db/con_mysql.js:5:8)
at Module._compile (module.js:446:26)
at Object..js (module.js:464:10)
at Module.load (module.js:353:31)
at Function._load (module.js:311:12)
at Array.0 (module.js:484:10)
at EventEmitter._tickCallback (node.js:190:38)
how can I resolve this problem?
I have installed mysql module like this:
# npm install mysql

deprecated: connect() is now done automatically.
Just try this:
client.createClient({'host':'localhost','port':3306,'user':'root','password':'root'});
The Error above states that it will automatically connect. You don't need to (and obviously cannot) call the connect() function.

Related

How to connect azure mysql server with nodeJS

I am trying to connect to a remote mysql server with nodejs
So far I am able to connect with mysql workbench 8.0, so no problem with mysql server. And I can easily connect to my local mysql-server (with "mysql2" module).
Here is something I've been trying to connect with remote mysql server provided by Azure. I followed the guides that is provided.
const mysql = require("mysql");
const fs = require("fs")
var connection = mysql.createConnection({
host: process.env.MYSQL_SERVER_HOST,
user: process.env.MYSQL_SERVER_USER,
password: process.env.MYSQL_SERVER_PASSWORD,
database: process.env.MYSQL_SERVER_DATABASE,
port:3306,
ssl: { ca: fs.readFileSync("./certificates/DigiCertGlobalRootCA.crt.pem")}
});
// This is how I am connecting to my local mysql-server which is working fine
// // const connection = mysql.createConnection({
// host: 'localhost',
// user: 'root',
// password: process.env.LOCAL_MYSQL_SERVER_PASSWORD,
// database: 'db',
// port: '3306'
// });
connection.connect((error) => {
if (error) {
console.log("mysql error")
console.log(error)
}
else {
console.log("Mysql Ready")
}
});
module.exports = connection;
Here I am using mysql package because many articles on web suggested it but I even used mysql2 and nothing happened. I even changed the networking setting and allowed my IP address for access(this wasn't necessary though).
Error logs:
mysql error
Error: connect ETIMEDOUT
at Connection._handleConnectTimeout (path\node_modules\mysql\lib\Connection.js:409:13)
at Object.onceWrapper (node:events:641:28)
at Socket.emit (node:events:527:28)
at Socket._onTimeout (node:net:516:8)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
--------------------
at Protocol._enqueue (path\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (path\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at Connection.connect (path\node_modules\mysql\lib\Connection.js:116:18)
at Object.<anonymous> (path\packnary\database\mysql.js:26:12)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
I connected Azure SQL database to the nodejs without using code.
I followed below procedure:
I have created azure blank nodeJs webapp in visual studio.
It run successfully. after that I go to overview of the webapp and selected connected services and clicked on a add a service dependency option and searched for azure sql database.
Image for reference:
select the azure sql data and click on next button.
login to azure account and select which database we need to connect.
Image for reference:
Enter the details required in the next window and click on next.
Image for reference:
Select the changes according to the requirements and click on next.
Image for reference:
It is connected successfully.
Image for reference:

Error as connect ECONNREFUSED when using node.js and MySQL

I'm trying to create a link between node.js and mysql. I get an error as connect ECONNREFUSED. how to solve ths?
CODE:
var mysql = require('mysql');
var conn = mysql.createConnection({
host : "192.164.0.114",
user : "supriya",
password : "root123#",
database: "student"
}
);
var queryString = "SELECT * FROM studata";
conn.query("someurlhere",queryString, function(error, results)
{
if(error)
{
throw error;
}
else {
console.log(results);
}
})
conn.end();
Error is:
Error: connect ECONNREFUSED
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
--------------------
at Protocol._enqueue (/home/supriya/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/home/supriya/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/home/supriya/node_modules/mysql/lib/Connection.js:109:18)
at Connection._implyConnect (/home/supriya/node_modules/mysql/lib/Connection.js:387:10)
at Connection.query (/home/supriya/node_modules/mysql/lib/Connection.js:174:8)
at Object.<anonymous> (/home/supriya/node_js/example2.js:19:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
I had the same problem. I invoked node server.js, which says
It's Started on PORT 3000 Problem with MySQLError: connect
ECONNREFUSED
By first line, I assumed, intially, it starts mysql server. However, that is not the case. it starts node server, which tries to connect to mysql server and node server says ECONNREFUSED. Clearly, mysql server was not running. I found this, when I logged in, as root, in mysql workbench and tried to execute simple query. There in the corner it said, "..at port 3306, it is not connected" or sth like that.
So, conclusion is starting server.js on some port starts node server and not mysql server.

node refuses to find mysql from script

I want to achieve that node prints me a table from MySql on my Windows 7 (64bit) machine but fail. Sorry for the long post in advance, I tried to be complete, also I failed to find this error in the forum. The optimistic mysql.js file I typed in Notepad++ was
var mysql = require('node-mysql');
var connectParams = {'hostname' : 'localhost','user' : 'dev','password': 'dev','database' : 'upandrunning'};
var db = new mysql.Database(connectParams);
db.connect( function(err) {
if(err) return console.log('Failed to connect ' + err);
this.query()
.select(['id', 'user_login'])
.from('users')
.execute(
function(err, rows, columns){
if(err) return console.log('err on query ' + err);
console.log(rows);
})});
Node keeps returning
C:\dev\nodejs\0.10\tutorials\node-up-and-running>node tutorials\node-up-and-running\mysql.js
module.js:340
throw err;
^
Error: Cannot find module 'C:\dev\nodejs\0.10\tutorials\node-up-and-running\tutorials\node-up-and-running\mysql.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
Why??
Before the node command I told Squirrel to do
drop database if exists upandrunning;
create database upandrunning;
grant all privileges on upandrunning.* to 'dev'#'%' identified by 'dev';
use upandrunning;
create table users(
id int auto_increment primary key,
user_login varchar(25),
user_nicename varchar(75)
);
using my localhost root account (bad), but all seemed fine because squirrel object tab showed new upandrunning db.
Node.exe is on C:\dev\nodejs\0.10\ but from dos prompt:
C:\dev\nodejs\0.10\tutorials\node-up-and-running>node -v
gives
v0.10.26
My file mysql.js has been reduced to the mere
var mysql = require('node-mysql');
where the error must be. I ran the following commands from C:\dev\nodejs\0.10\tutorials\node-up-and-running>
npm install -g mysql
npm install -g node-mysql
npm install -g db-mysql
These were the ones i could find.
After each install the same error above.
Any suggestions please how to make node cooperate?
I admit I lack node trouble shooting skills, but studying module.js, should not be necessary.
Also, do you know of, and enjoy working in, a free and easy to work with code completion ide for node?
And is there some way to debug other than console.log() ?.
Lastly what are your ideas on layout conventions for reducing the closing brackets because they hurt the eyes.
The site suggested From NodeJS require a global module/package
but how do i get the node_path variable on dos prompt and how to set it:
C:\dev\nodejs\0.10\tutorials\node-up-and-running>set NODE_PATH
Environment variable NODE_PATH not defined
Ok set NODE_PATH=c:\dev\nodejs\0.10
C:\dev\nodejs\0.10\tutorials\node-up-and-running>node tutorials\node-up-and-running\mysql.js
'node' is not recognized as an internal or external command, operable program or batch file.
Closing and reopening dos makes this go away.
C:\dev\nodejs\0.10>set NODE_PATH=%NODE_PATH%;C:\dev\nodejs\0.10\node_modules
And it works.. But now it fails on
var mysql = require('mysql');
var connectParams = {'hostname' : 'localhost','user' : 'dev','password': 'dev','database' : 'upandrunning'};
var db = new mysql.Database(connectParams);
C:\dev\nodejs\0.10\mysql.js:3
var db = new mysql.Database(connectParams);
^
TypeError: undefined is not a function
at Object.<anonymous> (C:\dev\nodejs\0.10\mysql.js:3:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
and if i remove the new it says
C:\dev\nodejs\0.10\mysql.js:3
var db = mysql.Database(connectParams);
^
TypeError: Object # has no method 'Database'
at Object. (C:\dev\nodejs\0.10\mysql.js:3:17)
Using the REPL:
var mysql = require('mysql');
undefined
var connectParams = {'hostname' : 'localhost','user' : 'dev','password': 'dev'
,'database' : 'upandrunning'};
undefined
var db = new mysql.Database(connectParams);
TypeError: undefined is not a function
at repl:1:10
at REPLServer.self.eval (repl.js:110:21)
at repl.js:249:20
at REPLServer.self.eval (repl.js:122:7)
at Interface. (repl.js:239:12)
at Interface.EventEmitter.emit (events.js:95:17)
at Interface._onLine (readline.js:202:10)
at Interface._line (readline.js:531:8)
at Interface._ttyWrite (readline.js:760:14)
at ReadStream.onkeypress (readline.js:99:10)
Aren't you supposed to create the connection like this.. ?
connection = mysql.createConnection({
host : 'localhost',
user : 'node',
password : 'UnPassword',
database: 'nodesql'
});

Cannot connect to MySQL db with nodejs (openshift app)

I have a nodejs (with express) openshift app that has a MySQL database (because that is what I am most familiar with), and I cannot figure out how to connect to it on the local environment. My last project I used a php framework with mamp to connect to the local database. What is the equivalent for node? This is the code I have to connect:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
port : '3307',
database : 'test'
});
connection.connect( function(err){
if (err){
throw err;
}
else {
console.log('Connected');
}
});
Here is the error when trying to connect locally:
Error: connect ETIMEDOUT
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
--------------------
at Protocol._enqueue (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/Protocol.js:110:26)
at Protocol.handshake (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/Protocol.js:42:41)
at Connection.connect (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/Connection.js:98:18)
at Object.<anonymous> (/Users/brandonmoffitt/stembudsnode/server.js:16:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
I am guessing that because I am trying to locally connect to the MySQL db set up by openshift, that I am receiving errors. I just dont know what else to try here. I have tried it without the password as well.
If I switch to localhost for the host, this is the error I receive:
Error: ER_DBACCESS_DENIED_ERROR: Access denied for user ''#'localhost' to database 'stembuds'
at Handshake.Sequence._packetToError (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/sequences/Sequence.js:30:14)
at Handshake.ErrorPacket (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/sequences/Handshake.js:91:18)
at Protocol._parsePacket (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/Protocol.js:202:24)
at Parser.write (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/Parser.js:62:12)
at Protocol.write (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/Protocol.js:37:16)
at Socket.<anonymous> (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/Connection.js:72:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:736:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
--------------------
at Protocol._enqueue (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/Protocol.js:110:26)
at Protocol.handshake (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/protocol/Protocol.js:42:41)
at Connection.connect (/Users/brandonmoffitt/stembudsnode/node_modules/mysql/lib/Connection.js:98:18)
at Object.<anonymous> (/Users/brandonmoffitt/stembudsnode/server.js:16:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
Sorry for the length of this post, I just have no idea why it isnt working.
EDIT:
I ssh'ed into the openshift shell to look at the mysql settings. When I do the 'show grants\g' command, this is what I receive:
Grants for adminMYXaSuf#127.11.28.130
GRANT ALL PRIVILEGES ON *.* TO 'adminMYXaSuf'#'127.11.28.130' IDENTIFIED BY PASSWORD '*D0CE5FA2AAD801A33C9190D0B615CC92F364BE6B' WITH GRANT OPTION
This password is different than the one openshift provided.
did you read their doc?.
if you have load balancer, your mysql will install on another gear.
you need to use the env variable when you install the cartridge
port
OPENSHIFT_MYSQL_DB_PORT=44331
host
OPENSHIFT_MYSQL_DB_HOST=12345600a4382ec97a10000f7-somehost.rhcloud.com
OPENSHIFT_MYSQL_DB_PASSWORD=somerandompassword
username
OPENSHIFT_MYSQL_DB_USERNAME=yourusername
pass the variable when you start your app as args.
look at the example for node
https://github.com/openshift-quickstart/nodejs-example/blob/master/server.js
just use the env variable like process.env.OPENSHIFT_MYSQL_DB_HOST to replace the string in the database connection.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : process.env.OPENSHIFT_MYSQL_DB_HOST,
user : process.env.OPENSHIFT_MYSQL_DB_USERNAME,
password : process.env.OPENSHIFT_MYSQL_DB_PASSWORD,
port : process.env.OPENSHIFT_MYSQL_DB_PORT,
database : process.env.OPENSHIFT_APP_NAME
});
It looks like you are running this on your local computer? If you want to connect to your mysql database on OpenShift from your local computer, you need to use the rhc port-forward command, and look at the port it gives you for mysql, so then you would set the ip to 127.0.0.1 and the port to something like 3307 or whatever it gives you locally. Keep the port-forward command running while you test the connection. You could also try pushing your code up to openshift and run it with the values that you have (or use the mysql environment variables that you can get with env | grep MYSQL on your gear) and then see if it works.
127.x.x.x are not publicly available ip addresses, they are private to that server, that is why you can't connect to it from your machine, and need to use the rhc port-forward command
This works for me:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
port : '3306',
user : 'admind4DxYD5',
password : 'some_pass',
database : 'developercorey'
});
connection.connect( function(err){
if (err){
throw err;
}
else {
console.log('Connected');
}
});

Can't install Node.js plugin on Ubuntu 12.04

I have installed this database plugin for Node.js called 'db-mysql' and I've gone through all the steps mentioned on the site without getting errors, which must mean that the plugin is installed. But when I run my .js file (given below) in the Apache server I get this error.
Error: Cannot find module 'db-mysql'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/var/www/server.js:4:13)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
Here is the sample code I'm running.
var http = require("http");
var mysql = require("db-mysql");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
//Database Connectivity//
new mysql.Database({
hostname: 'localhost',
user: 'root',
password: '',
database: 'test'
}).on('error', function(error) {
console.log('ERROR: ' + error);
}).on('ready', function(server) {
console.log('Connected to ' + server.hostname + ' (' + server.version + ')');
}).connect();
///////////////////////
response.end();
}).listen(8889);
Did I miss anything during installation?
If you install module like in example
npm install db-mysql
Node will search it here
./project_root/node_modules/db-mysql
So make sure this path is correct in your case.
Other option is to install it globally by using -g flag
npm install db-mysql -g
Simply make a sym link that points to where your modules are physically installed
Name this link node_modules and put it inside the folder of your project