NodeJS xdevapi - Creating Connection to MySQL Database - mysql

I've been using the official MySQL NPM package found here: https://www.npmjs.com/package/#mysql/xdevapi.
However, I can't seem to make a connection to the server. Here's the current error message I get:
Error: The server connection is not using the X Protocol.
Make sure you are connecting to the correct port and using a MySQL 5.7.12 (or higher) server intance.
Here is the code that generates that issue:
const db = mysqlx.getSession('root#localhost:33060/schemaname').then(session => {
console.log('SESSION STARTED!!');
});
This is just a test database without a password so I don't think the password is the issue. Also, I've made sure I'm using the right port and the MySQL version is 8.x.x so I don't think that is the issue. I created a database using the app Dbngin and I verified I could connect to the database by running the following command in my terminal: mysql -u root -h 127.0.0.1 --port=33060 -p which worked. I'm also running this on my Mac.
Update:
I've also tried passing a config object without much luck:
const config = {
user: 'root',
password: '',
host: 'localhost',
port: 33060,
schema: 'schemaname'
};
const db = mysqlx.getSession(config).then(session => {
console.log('SESSION STARTED!!');
});
Unfortunately, this code produces the same error above.

I tried it out myself and got the same error because you are using the wrong port. It could be you changed the default port, but the default port is: 3306 and not 33060 although I have to use port 33060 while my port is 3306.
X-protocal requires you to multiply your port by 10 I see here: https://dev.mysql.com/doc/mysql-port-reference/en/mysql-ports-reference-tables.html. So if your original port is 33060 I guess it should be 330600.
You could try this command SHOW VARIABLES LIKE 'mysqlx_port';

Related

How do I give access to my partner to my local MySQL database?

My partner and I are using MySQL, Express, and Node while working with a database that is setup on my local machine using MySQL workbench. Below is the code I use to connect to the database.
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '****',
database: 'events',
port: '3306'
})
We tried for a little bit to fix the issue but didn't figure it out before we agreed to meet tomorrow to try and get it to work.
Below is what I have come up with so far to see tomorrow if it fixes the issue:
Added 'bind-address = 0.0.0.0' to the my.ini file directly underneath the [mysql] section
Created a root2 user for my partner to use in place of root user in his connection code with host as % instead of localhost with command GRANT ALL PRIVILEGES ON events.* TO 'root2'#'%'; on the mysql command line
Adjusted firewall settings to account for port 3306
Would the last step be to change my partner's host: 'localhost' to the ip address of my machine? Would it be easier/necessary for my partner to connect using MySQL workbench or does he need to download anything else for it to work?
Check the error log for your MySQL server.
Select the host user from mysql.user.
Check your firewalld(linux), then shutdown. Check my.ini(windows) bind-address.

Node.js establish connection to remote mysql server using tunnel-ssh

I am using the tunnel-ssh module to establish connection to the remote mysql database using node.js. The documentation is poor and I am not able to establish a connection. Here is the code snippet:
var tunnel = require('tunnel-ssh')
var server = tunnel.tunnel(config.sshData, function(err, result) {console.log('connected'});
Here is my sshData object.
config.sshData = {host : 'serverxyz.web-hosting.com', username : 'xyz', password : 'xyz',
srcPort: 3307, dstPort : 21098}
The dstPort is 21098 as suggested by the namecheap documentation.
However I am getting timeout error and whenever I add this snippet:
server.on('error', function(err) {});
I get the error server.on is not a function. The remote connection is working fine on putty and SQLyog. Any procedure on how to establish successful connection would be of great help. Thanks!
Update
Got the database working by using the correct ports specified and by directly using ssh2 module with the code example given here
There is a misunderstanding with the namecheap documentation. 21098 is the ssh port, not the port the database is listening on. In order to use a non-standard ssh port, you will need to explicitly specify the port value like:
config.sshData = {
host: 'serverxyz.web-hosting.com',
port: 21098,
username: 'xyz',
password: 'xyz',
dstPort: 3306
};
Then you should be able to connect to localhost:3306 to access your remote database.

Node.js MySQL - Error: connect ECONNREFUSED

I use Node.js server side. I tried my code on localhost and everything works fine. I bought a server and installed Apache and node.js on it and test my web application there. I correctly changed the MySQL connection configurations from localhost to the server configurations.
I test my web application with this configuration:
var mysql = require('mysql');
var mysqlConnection;
function new_mysqlConnection() {
mysqlConnection = mysql.createConnection({
host : 'myurl.at',
user : 'myusername',
database : 'mydatabase',
password : 'mypassword'
});
}
I start the node.js server with:
$ node server.js
When I load the page, it's correctly displayed, but when Node.js try to connect to the database I always got the following error:
Error: connect ECONNREFUSED
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
--------------------
at Protocol._enqueue (/var/www/node_modules/mysql/lib/protocol/Protocol.js:135:48)
at Protocol.handshake (/var/www/node_modules/mysql/lib/protocol/Protocol.js:52:41)
at Connection.connect (/var/www/node_modules/mysql/lib/Connection.js:119:18)
at reconnectDb (/var/www/server.js:319:18)
at app.get.email (/var/www/server.js:109:2)
at Layer.handle [as handle_request] (/var/www/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/var/www/node_modules/express/lib/router/index.js:302:13)
at /var/www/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/var/www/node_modules/express/lib/router/index.js:321:12)
at next (/var/www/node_modules/express/lib/router/index.js:261:10)
You need to add the value of socket path to the config object:
socketPath: '/var/run/mysqld/mysqld.sock'
In MAMP, you go to http://localhost:8888/MAMP, and you find:
/Applications/MAMP/tmp/mysql/mysql.sock
At the end you have:
var connection = mysql.createConnection({
host : config.host,
user : config.user,
password : config.pass,
database : config.db,
socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'
});
I was having same problem but I solved this by changed
host: 'localhost'
to
host: '127.0.0.1'
Check for your MySQL port in your server.
In MAMP, by default it uses 8889.
Add that to your connection config.
Your MySQL config should look like this.
this.pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost',
user: 'root',
password: 'root',
database: 'todo',
port: '8889'
});
Check your xampp server mysql is running or not
I fix it by the following code after a struggle of two days. ( Just giving my solution, you might have another solution as well.)
Follow these steps as well.
Delete all node_modules
Run "npm audit --force"
install npm packages by "npm install"
const sequelize = new Sequelize("test", "root", "root", {
host: "127.0.0.1",
dialect: "mysql",
port: "8889",
connectionLimit: 10,
socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock"
});
Note: I am using sequelize with graphql (NODEJS).
if using using express and MySQL. port should be same as your MySQL port.
The default MySQL port is 3306.
let defaultPORT = 3306;
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'yourMYSQLUser',
password : 'yourMYSQLPassword'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
var server = app.listen( defaultPORT, function() {
console.log( defaultPORT)
});
I would recommend to add the port in the below table of yours;
const pool=mysql.createPool({
host: '127.0.0.1',
user: 'root',
database: 'node-complete',
port: "3307",
password: 'Aditya2000#'
});
The port number is to be taken from your MySql Workbench from the homepage table of it which should shows:
Local Instance MySql root localhost: 3307 -> this localhost number
has to be written there.
In most cases, your host should match your bind-address in the MySQL config file.
if your bind-address is 0.0.0.0 or 127.0.0.1 then setting host to 'localhost' should work. but if your bind-address is your actual IP address then you should add your IP address instead.
var sql_con = mysql.createConnection({
host: "ip address",// should be the same as bind-address
user: "jeffery",
password: "damnthing",
database: "KOKATOOO"
});
I had the same issue turns out mysql was not running.
Make sure it's running by:
$ systemctl status mysqld
If you see this:
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: failed (Result: start-limit) since Tue 2020-08-18 12:12:29 CDT; 32min ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 18668 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS (code=exited, status=2)
Process: 18650 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 18668 (code=exited, status=2)
Status: "SERVER_BOOTING"
Then the service is not running, to run enter:
$ systemctl start mysqld
I Also have same problem in google cloud with nginx
changed
host: 'localhost'
to
host : 'cloud_instance_private_ip'
may help some one with same problem
It's probably course from the absence of port and database.
first I wrote:
host,
user,
password and no database and port.
Here you need to specified what is your database name, what is your port number.
So the total must be:
1. host
2. user
3. password
4. database
5. port
It's works for me, try it if it works for you too.
I 'm also have same problem but i found the solution by adding:
port:"80"
I connect with node.js to the server php mysql using this code:
var mysql=require('mysql');`
var connection=mysql.createConnection({
port:"80",
host:"localhost",
user:"root",
password:""
});
open services from the search bar.In there search for MySQL80.Right click on it and click on start.Now run the code.It should work.Most of the times the SQL service is inactive when the computer starts up
have experienced a similar issue where with the same configs, could connect from local -> mysql server but not when deployed as cronjob to k8s cluster. Not sure why but workaround was to add sleep 10 && before running application: args: ["-c", 'sleep 10 && node index.js']
I had same issues, and i resolved it by adding my port
Port: YOUR_PORT
had this same issue and I solved it by adding the port
I created a new user in PhpMyAdmin with a username as "user" and password as "". I set the host as "%" which allows connection from any host.
Use the IP address you find in the XAMPP control panel as the host in the node js code
I have used the IP address in the XAMPP control panel as the host in the database connection
This solved the problem and connected to the database
Maybe it will help someone, In my case I am using strapi app when I encountered this issue, I realized that I did not create database, So I am using Mamp I go to php my admin created db and updated database.js in config folder and now its working fine
In my case it was working locally, but now when deployed.
The problem was I hadn't updated the environment variables
I am facing the same problem but I have done that:
Turn ON your MySQL using XAMPP
Create a database that will mention in the code. (I have 'node js' named database.
By doing these, my code is worked perfectly.
You can see here

errorError: getaddrinfo ENOTFOUND - mysql

I'm running a server on c9.io using Node.js and trying to connect to Mysql
I guess I get this error:
Error: getaddrinfo ENOTFOUND
because the connection to the db is wrong.
I'm using this:
var connection = mysql.createConnection({
host: "REMOTE_ADDR",
user: "MYUSERNAME", // this is replaced by my username
database: "c9",
port: 3306
});
Any idea what's wrong?
Thanks!
After one hour, and I don't know why, I found the issue.
In my case I replaced
host: 'localhost'
by
host: '127.0.0.1'
I know it's been a while since this was asked but I spent the better part of today trying to fix this. What to check for:
Within your nodejs source:
Try it without the 'port' option unless on your db VM, MySQL is
listening on a port besides 3306. I had this option specified but had
connection problems until I removed it. And 3306 is already the
default value for the option anyway.
Try it with the actual host IP in the host 'option'. I was using an actual domain name and, more often than not, node-mysql would throw
the same exact "errorError: getaddrinfo ENOTFOUND" When I used the IP
address, no more errors. Also, I did not get this error while on
Ubuntu instances in AWS. As soon as I switched over to Ubuntu VMs in
Azure, I got the problem.
Set the "debug" connection option to true which will give you a verbose trace of what's happening during the connection
On your db VM/Box/Instance:
Ensure that MySQL is listening on the right port
If you're seeing the error when trying to make concurrent connections using a pool, check that your max_connections and max_user_connections haven't been changed from the default settings in my.conf
Monitor "SHOW PROCESSLIST;" in MySQL to see if you see any issues there
This code works for me.
var mysql = require('mysql');
var con = mysql.createConnection({
host: '127.0.0.1',
port: '3306',
user: 'yourUsername',
password: '**********'
});
con.connect(function(err){
if(err) throw err;
console.log('connected!');
});
the host and port name find them in your mysql server.
in-place of '127.0.0.1' you can use 'localhost'
I was facing this issue. I did fix it simply you have to change your configuration of a connection string like if you are running on local machine try
host:'localhost' or host:'127.0.0.1'
...and set your user name and if you want this to publish your code on server then give the host according to server if in docker container give it name host:'db'.
I almost spend two hours to understand what is the problem with the mysql database. I am using Windows cmd.
I tried multiple ways e.g
npm install mysql2
Changing localhost to 127.0.0.1
Refreshing node
so in order to resolve this issue
[Error: getaddrinfo ENOTFOUND 127.0.0.1:3306]
I open XAMPP and start the MySQL database then manually check the credentials and works fine for me.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'test',
password: 'test123',
});

node.js mysql error: ECONNREFUSED

Why can't I connect to the mysql server?
On the same server an Apache/PHP server is running and it connects without problems!?
var mysql_link = {
host : 'localhost',
port : 3308,
database: 'nodetest',
user : 'root',
password : 'xxx'
};
var connection = mysql.createConnection(mysql_link);
connection.connect(function(err){
console.log(err);
if(err != null){
response.write('Error connecting to mysql:' + err+'\n');
}
});
connection.end();
error
{ [Error: connect ECONNREFUSED]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
fatal: true }
update
root#dyntest-amd-6000-8gb /var/www/node/dyntest # ps ax | grep mysqld
7928 pts/0 S+ 0:00 grep mysqld
28942 ? S 0:00 /bin/sh /usr/local/mysql/bin/mysqld_safe --datadir=/var/lib/mysql --pid-file=/var/run/mysqld/mysqld.pid
29800 ? Sl 17:31 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/var/lib/mysql --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/var/lib/mysql/mysql-error.log --open-files-limit=65535 --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306
I know this question has been answered, but for me the problem was that the mysql server listens on a Unix socket not on a tcp socket. So the solution was to add:
port: '/var/run/mysqld/mysqld.sock'
to the connection options.
If this has worked before, my first guess would be that you've already got a copy of your node.js script running in the background which is holding the connection.
I believe connection refused is a tcp/ip error message, rather than something from MySQL which suggests that it is either not running or is running on another port or with sockets.
Could you try telnet'ing to port 3308? To see if the server is running on that port?
telnet localhost 3308
Can you also try:
mysql -hlocalhost -uroot -pxxx
Overview
For anyone else having this problem and is running mamp. I suspected the problem had to do with the network and not MySQL or Node.js.
Solution
If you open MAMP and click MySQL in the left navigation panel it will pull up the MySQL options page. In the center of the page you will see a checkbox that says,
"Allow network access to MySQL".
Check this box and then restart your MAMP. At this point you can now test your connection to MySQL with telnet or a node.js script.
Hint
Remember you can check which port your MySQL is running on by opening MAMP and clicking the ports link on the left navigation panel.
Visual Aid
For some very odd reason, my computer only allowed me to have port 3306 as default port for my connection in order for it to work.
Mac OS on M1 MacBook Pro here with MySQL installation via brew:
Changing the host from 'localhost' to '127.0.0.1' and creating a different user with a password solved this issue for me.
For some reason I cannot connect to my DB with root user and no password.
I created the new user on MySQL Workbench, but you can create a new user with admin privileges via the mysql CLI also.
Just google it.
This is how my backend looks:
const express = require('express');
const mysql = require('mysql');
const app = express();
const port = 3500;
const db = mysql.createConnection({
host: '127.0.0.1',
user: 'admin',
password: 'admin',
});
db.connect((err) => {
if (err) throw err;
console.log('connected to database');
});
app.listen(port, () => {
console.log('server listening on port 3500');
});
I wanted to comment my solution here, just in case there were people as newbie as me in databases.
I was getting this error because I had installed the mysql NPM package correctly but I hadn't installed any implementation of MySQL on my computer (I didn't know I had to).
I'm using Arch Linux so, in my case, with the NPM package already installed in my project, I did pacman -Syu mariadb (MariaDB is the default implementation of MySQL in Arch Linux) and then configured it following the guide.
Then, you can use the root user you just configured or create a new one to use in your project. For the latter:
Enter mysql CLI by running mysql -u root -p.
Enter the password for root user.
Create a new database with CREATE DATABASE mydatabase;.
Create a new user with CREATE USER test IDENTIFIED BY "testpass";.
Grant privileges to test user to use your new database with GRANT ALL PRIVILEGES ON mydatabase.* TO test#localhost IDENTIFIED BY "testpass";. See for more information on this.
And then, in my project, I would have:
let connection = mysql.createConnection({
host: "localhost",
user: "test",
password: "testpass",
database: "mydatabase"
});
If you are using MAMP please note that mysql default db_port is set to 8889 so you for this purpose I had to change it to 3306 (or whatever your app mysql db_port is set to).
My issue was that node server was connecting using port 3306, so it was giving the error below then crashing but mysql was up and seemed to establishing a connection through localhost, although I couldnt test it because node server was down.
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
Once I changed the port on MAMP mysql from 8889 to 3306, node server established connection through port 3000 and giving the statement below:
server running on port 3000
The solution is: 2
I use Windows 10 and I have Windows Subsystem For Linux (WSFL). I can execute my project from the WSFL console, but my MySQL is installed in Windows and they can not connect, however when I execute my project from a Windows console then it works without any problems.