Databases

Node.js MySQL

Using MySQL

Node.js MySQL integration uses mysql2 for relational queries.

Introduction to MySQL in Node.js

MySQL is a popular open-source relational database management system. In Node.js, the mysql2 package is widely used for integrating MySQL databases, providing a promise-based API for executing SQL queries efficiently. This guide will walk you through setting up MySQL with Node.js, performing queries, and handling results.

Installing mysql2

To start using MySQL in your Node.js application, you need to install the mysql2 package. This can be done using npm:

Connecting to a MySQL Database

Once you have installed mysql2, you can connect to a MySQL database using the following code snippet. Make sure to replace the placeholders with your actual database credentials.

Performing a Simple Query

Once connected, you can execute SQL queries. Here is an example of a simple query to select all records from a table called users.

Using Promises with mysql2

The mysql2 package also supports promises, which can simplify handling asynchronous operations. Here is an example using promises to perform the same query:

Closing the Database Connection

It is essential to close the database connection once you are done with your queries to free up resources. This can be done using the connection.end() method.

Previous
MongoDB