Skip to main content

Connecting to MySQL

In this tutorial, we will learn how to connect to a MySQL database using Node.js. We'll start by understanding the basics of MySQL and then move on to installing and setting it up. Following that, we'll dive into how to use Node.js to connect and interact with this database.

What is MySQL?

MySQL is one of the most popular open-source relational database management systems (RDBMS) widely used in web applications to store and manage data in a structured format.

Setting Up MySQL

Before we can connect to MySQL using Node.js, we need to ensure that MySQL is installed and properly set up on your machine. If it's not already installed, you can download it from the official MySQL website. Follow the installation instructions provided on the website.

Once installed, start the MySQL server.

Node.js MySQL Module

Node.js provides a module named mysql that helps to connect and perform operations on the MySQL database. To install this module, open your terminal or command prompt and type the following command:

npm install mysql

Connecting to MySQL Database

After installing the mysql module, we can use it to establish a connection to the MySQL database. Here is the basic syntax:

var mysql = require('mysql');

var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "yourdatabase"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});

In the above code:

  • require('mysql') is used to include the MySQL module.
  • createConnection() method is used to create a connection object.
  • host, user, password, and database are properties of this object.
  • connect() method is used to establish the connection with the database.

Error Handling

It's important to handle errors that may occur when trying to connect to the database. This can be done by listening for the error event on the connection object:

con.on('error', function(err) {
console.log('db error', err);
if(err.code === 'PROTOCOL_CONNECTION_LOST') {
handleDisconnect();
} else {
throw err;
}
});

Querying the Database

Once the connection is established, you can query the database using the query() method:

con.query('SELECT * FROM yourtable', function (err, result) {
if (err) throw err;
console.log(result);
});

In the above example, we are using a basic SQL query to fetch all records from the specified table. The result is then logged to the console.

Remember to close the connection once you're done interacting with the database:

con.end(function(err) {
if (err) throw err;
console.log('Connection closed');
});

Conclusion

That's it! You now know how to connect to a MySQL database using Node.js, handle errors, and query the database. Practice with different SQL queries and operations to get comfortable with using MySQL with Node.js. Happy coding!