How to connect mysql in lambda nodejs
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1304',
database: 'DemoDB'
})
connection.connect(function (err) {
if (!err) {
console.log("Database connected ... ");
}
else {
console.log("Error connecting database : " + err.message);
}
});
const sql = "CREATE TABLE MESSAGE (message VARCHAR(255))";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
If this MySQL server is installed locally in your computer then here's a few troubleshooting that you can try:
Make sure your mysql services is running.
Make sure you can connect to the mysql db using that host+port+user+password combination - test connect to it using command line or sql tools like SQLyog etc.
Make sure that the mysql program and port it's using not blocked by firewall - if you have a strict firewall then you possibly need to do firewall exception for mysqld, mysqld-nt and port 3306.
To check what port is your MySQL running on, you have to look for my.ini or my.cnf file (usually located in MySQL folder or MySQL/Data folder). In that file you need to find port=XXXX and there are two of them. Make sure both values of port= are the same.
The idea here is first to make sure your MySQL server is up and running before connecting through node.js because judging from the error message that you've received, it seems like its not a problem from node.js.
AWS Lambda function runs on the cloud (some remote server) whereas you are providing localhost as the Database host which means that your MySQL server is running on your PC so that is why the connection is not establishing. You have to provide the IP of your PC instead of localhost for things to work properly.
Related
guys! I'm a coding begineer, and I'm trying to connect my nodejs app to the database I've created with Cpanel (PHP) (my host is Namecheap).
It's very easy to create a mysql workbrench localhost conenction, but I cannot do it with an external server, and I'm looking for any guidance. If I need to deploy my code and add it to the file manager in CPanel, which is the information I need to change to connect my code with the CPanel Database that I've created.
This is the code that I have right now with a localhost DB that I have created in my computer, and is working perfectly fine:
`
var mysql = require('mysql');
const dotenv = require('dotenv').config();
const connection = mysql.createConnection({
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PW,
database : process.env.DB_DATABASE
});
const connectionError = connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
module.exports.connection = connection;
module.exports.connectionError = connectionError;
`
My questions are:
How to connect my code with the Namecheap server?
Which should be my host (I think I can get this in the variables from PHP, but I'm not sure if this is an IP or it could be a string like "server254.web-hosting.com"
Which should be my user? I'm not sure if this is the server user, the user that appear in the SSH file, or the database user.
Is the password the one from my database user or the one from Cpanel?
Should I have a port or is it the default?
As this documentation says, I tryed to connect to a database using the Workbench MySQL client, but for some reason looks like my user don't have all the privilegies to access, and I give it all the privilegies from the Database in Cpanel (I tryed also creating a user from PHP but I cannot do it).
I tryed using a SSH-tunneling, neither it works, I guess I'm just adding the incorrect information, but I would like to make sure.
I have issue when i try to connect to the database on remote server.
My code:
const mysql = require('mysql');
const database = mysql.createPool({
host: 'localhost',
user: 'user',
password: 'pass',
database: 'db'
});
database.getConnection(function (err, connection) {
if (!err) {
console.log('Database is connected ...');
} else {
console.log('Error connecting database ...');
}
});
The credentials for connection in code is faked. With the right credentials I have, I login successfully on phpMyAdmin on remote server, on datebase that I want to connect. Credentials is good.
When I run script, return this error:
view error
Also, when I input credentials for connection with my local database, everything work perfect.
As pointed out by Luuk, you need to replace the localhost with the actual IP address of the remote database server and the port on which the database server is running.
For example -
const database = mysql.createPool({
host: '123.234.121.234',
port : '3306',
user: 'user',
password: 'pass',
database: 'db'
});
Also, make sure the port is whitelisted and can be accessed over the network. Heres a tiny little diagram for explanation.
phpmyadmin runs on the same machine as your MySQL server, so it can connect to the server using the generic host name localhost.
I guess, from your question, that your nodejs program runs on some other machine (your personal machine, maybe?). That takes some special-purpose setup to do.
You must use the server's actual hostname in your host: property, not localhost.
MySQL login credentials aren't just username/password. They are host/username/password. You may need to create a new set of credentials for remote access so your nodejs program can get in. Read this: https://webmasters.stackexchange.com/questions/2242/how-to-create-separate-users-in-phpmyadmin-each-one-cant-see-others-databases
If your MySQL server runs on a rented server at some cloud or hosting service, you may need to open up a firewall to allow your machine to connect. If you're on a hosting service, ask their customer support krewe about that. On a cloud service, you want to open port 3306. Look up how to do that in their documentation. (It may be a gnarly configuration task).
Your easiest way of troubleshooting this is to use some MyQSL client program (like MySQL Workbench or HeidiSQL) on your own machine. when you get that to connect, you can use the same credentials in your createPool() call.
I am getting error SequelizeConnectionError: connect ETIMEDOUT when trying to connect to a remote mysql db with sequelize.
Connection can be established successfully when I try to connect to my local mysql db.
I'm using sequelize's default db connection code new Sequelize(...) contained within models/index.js, with the following config (filled up with the correct values):
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
I tried connecting to the remote db with a simple php script and it worked (so we can rule out issues on the remote db server side)
Any ideas?
For me, I have to:
1) Define exact information of my database at the local server (Xamp/ Mamp). It means I must have the existing database to connect, user name and password is a privileged account in your database.
2) Xamp/ Mamp must be online (of course). Default ports will be taken by this local server, so try a different port for mysql 8889 instead of 3306.
And this is what I tried:
sequelize = new Sequelize('wohui', 'root', 'root', {
dialect: 'mysql',
host: 'localhost',
port: 8889
});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch((err) => {
console.log('Unable to connect to the database:', err);
});
I had the same problem, in my case it happened because I forgot to open the connection to mysql port 3306 in the inbound rules at my cloud provider
This error usually appears when the connection to the sql server is not established. Some things to take care of are :
Ensure mysql server is running in the host you are trying to connect to.
Ensure the host ip is correct.
Ensure that the port entered is correct.
Ensure that the firewall rules are defined correctly.
There could be couple of reasons for this, Listing out a few I have faced,
Remote root access not granted by the mysql server.
The configs are filtered by the environment, Which ideally is done by using the NODE_ENV variable, can you try running your server locally with prod config. In my case, I would do something like NODE_ENV=production node server.js. Assuming server.js is the start file. You can try logging the value's before new Sequelize(...), that might give a better idea as to what's going in.
I was facing the same issue. While in my case I gave a wrong port number (I didn't update my port number for the production database)
I had the same issue and my problem was in the ports. MySql had ports 3306 and in the config, i wrote port 3000 :D
Thanks for helped
Starting from scratch, I googled how to connect to a mysql database over ssh using node.js and the mysql library, and I came across this:
Node.js connecting through ssh
So I started a "screen" session, connected with the ssh command, and created the connection in a node script. However, I was getting an error. A comment below the accepted answer had the same issue:
I'm using a mac terminal, I typed 'screen', entered in the information you provided with my domain and password,and succesfully connected into my server via ssh. However, when I run my server.js node file the problem still persists. I'm receiving: { [Error: connect ECONNREFUSED] code: 'ECONNREFUSED', errno: 'ECONNREFUSED', syscall: 'connect', fatal: true } Is there a step here that I missed? I'm able to query successfully with this code on servers that don't require ssh.
And the response led me somewhere but did not completely explain what I need to do:
After you connected via ssh you need to connect your node.ja app to localhost. Because with that ssh command in screen you make port 3306 from mysql server available on your local machine
How exactly does one "connect your node.js app to localhost"? I saw that on the remote server side, I was getting channel 3: open failed: connect failed: Connection refused. So some sort of request was getting successfully sent to my remote server. However, something was failing. Googling led me to this answer:
SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"
The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.
So now I'm stuck. How does one cause a server to "listen" so that mysql can work over ssh?
Thanks!
FWIW tunneling mysql over ssh can be accomplished in-process with the mysql2 and ssh2 modules. For example:
var mysql = require('mysql2');
var Client = require('ssh2').Client;
var ssh = new Client();
ssh.on('ready', function() {
ssh.forwardOut(
// source address, this can usually be any valid address
'127.0.0.1',
// source port, this can be any valid port number
12345,
// destination address (localhost here refers to the SSH server)
'127.0.0.1',
// destination port
3306,
function (err, stream) {
if (err) throw err;
var sql = mysql.createConnection({
user: 'foo',
database: 'test',
stream: stream // <--- this is an important part
});
// use `sql` connection as usual
});
}).connect({
// ssh connection config ...
});
Also, since there is overhead with creating ssh connections, you might want to create an ssh connection pool for better reuse.
I'm really new to node.js and MySQL, and when I try to learn both at once... let's just say I need some help. ;)
I want to use the node-mysql module to dynamically edit a database via node.js. All the basic code is in place.
var http = require('http'),
mysql = require("mysql");
var connection = mysql.createConnection({
user: "root",
password: "",
database: "ballot"
});
http.createServer(function (request, response) {
request.on('end', function () {
connection.query('SELECT * FROM data;', function (error, rows, fields) {
response.writeHead(200, {
"Content-Type": "text/plain",
'Access-Control-Allow-Origin' : '*'
});
response.write(JSON.stringify(rows));
response.end();
});
});
}).listen(8080);
The problem is, I'm listening on port 8080, and localhost is of course port 80. Should I listen on port 80? If so, how do I do so without messing with Wamp? And how can I access the databases I create with PHPmyAdmin?
WAMP gives you a number of things, including MySQL and an apache web server with phpMyAdmin pre-configured.
By default the Apache web server listens on port 80 and the MySQL server listens on port 3306. With WAMP running, these ports will be taken. Your node process will be able to create a server listening on port 8080 as long as you have no other processes listening on port 8080. By default this should be fine and you will be able to access the node http server via http://localhost:8080
A connection with the MySQL database is established on port 3306. You just need to setup your database as you normally would through phpMyAdmin. By default this will be at http://localhost/phpMyAdmin which is running on the apache server on port 80.
Just to clarify, as your terminology seems slightly confused. Localhost in a host name. It's the location of the machine that you wish to talk with. The port number is completely separate and "localhost is of course port 80" doesn't make any sense. You can specify any valid port number for localhost. As I already mentioned, listening on port 8080 means you can access the node server through http://localhost:8080