Connect NodeJS App With MySQL Database Hosted on a Digital Ocean Droplet (Server)
Connect a Node.js application to a MySQL database hosted on a Linux server.
- Web Development
- Infrastructure
Note: This article assumes that you are familiar with Node.js, that you have or are planning to host your application or database in a Linux environment, and that you have a fair knowledge of the command-line interface.
For starters, let us create a new project and initialize it with npm:
npm init -y
Next, install the MySQL package using npm:
npm i --save mysql
Create an index.js file in your project root directory. Inside it, create a variable named
mysql, which will be an instance of the MySQL package:
const mysql = require("mysql");
Now, we need to create a connection object by supplying the following:
- host:
localhostif both the Node.js app and database exist on the same server, or the IP address of the server where the database is hosted - database: the name of the database
- user: the database username
- password: the database password
Here is how it would look:
const connection = mysql.createConnection({
host: "localhost",
user: "u53rname",
password: "pa55w0rd",
database: "food_db",
});
If all is well, we can now connect to the database:
connection.connect((err) => {
if (err) {
console.log("Connection error message: " + err.message);
return;
}
console.log("Connected!");
});
The code checks for an error while connecting to the database on the specified host and displays the error message in the console if there is one. Otherwise, the connection was successful and it displays just that.
Go ahead and try the connection by querying a table in the database:
const queryString = "select * from tbl_nig_dishes";
connection.query(queryString, (err, res, fields) => {
if (err) {
console.log("Error: " + err);
return;
}
console.log("Here is the result of the query:");
console.log("===========================================");
console.log(res);
console.log("===========================================");
});
You should see the result of the query in your console.
Don’t forget to close the connection:
connection.end();
That should get the work done.
Pro tips
- Keep credentials safe using environment variables. Check out dotenv.
- Follow best practices and use newer JavaScript syntax (ES6+).
You can get the complete code from GitHub.
I hope this helps you. Thanks for reading.
Further resources
This post is also available on DEV.