MySQL is a popular relational database management system that is widely used in web applications. In this tutorial, we will guide you through the process of connecting MySQL to a Node.js server on Ubuntu 20.04.
Step 1: Install MySQL Server
The first step is to install the MySQL server on your Ubuntu 20.04 machine. You can install MySQL server by running the following command in the terminal:
sudo apt-get install mysql-server
Step 2: Start the MySQL Service
After installing the MySQL server, start the service using the following command:
sudo systemctl start mysql
Step 3: Configure MySQL Server
Once the MySQL service is started, you need to configure it by running the following command:
sudo mysql_secure_installation
This command will prompt you to set a root password, remove anonymous users, disallow remote root login, and remove the test database. It is recommended that you follow these prompts to secure your MySQL server.
Step 4: Install the MySQL NPM Package
To connect your Node.js server to the MySQL database, you will need to install the MySQL NPM package. You can install this package by running the following command:
npm install mysql
Step 5: Create a Connection Object
After installing the MySQL NPM package, you need to create a connection object in your Node.js server. This can be done using the following code:
const mysql = require(‘mysql’);
const connection = mysql.createConnection({
host: ‘localhost’,
user: ‘root’,
password: ‘yourpassword’,
database: ‘yourdatabase’
});
Replace ‘yourpassword’ and ‘yourdatabase’ with your MySQL root password and the name of the database you want to connect to.
Step 6: Test the Connection
Finally, test the connection by running the following code:
connection.connect((err) => {
if (err) {
console.error(‘Error connecting to MySQL database: ‘ + err.stack);
return;
}
console.log(‘Connected to MySQL database.’);
});
This code will log an error message if there is a problem connecting to the database or a success message if the connection is successful.
Conclusion:
In this tutorial, we have learned how to connect MySQL to a Node.js server on Ubuntu 20.04. By following the steps outlined in this tutorial, you should now be able to connect your Node.js server to a MySQL database, allowing you to store and retrieve data from the database in your web application.