Last modified: Jul 21, 2025 By Alexander Williams
Install MySQL2 in Node.js - Quick Guide
The mysql2 module is a popular Node.js library for connecting to MySQL databases. It is faster and more efficient than the original mysql
package.
This guide will walk you through installing and using mysql2 in your Node.js projects.
Prerequisites
Before installing mysql2, ensure you have:
- Node.js installed on your system
- npm (Node Package Manager) or yarn
- A MySQL database server running
If you need help setting up Node.js, check our guide on installing TypeScript in Node.js.
Install MySQL2 Using npm
Open your terminal and run this command in your project directory:
npm install mysql2
This will download and install the latest version of mysql2.
Install MySQL2 Using Yarn
If you prefer using yarn, run this command instead:
yarn add mysql2
Basic Usage Example
Here's how to connect to a MySQL database using mysql2:
// Import the mysql2 module
const mysql = require('mysql2');
// Create a connection pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
password: 'yourpassword',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// Get a connection from the pool
pool.getConnection((err, conn) => {
if (err) {
console.error('Error connecting:', err);
return;
}
console.log('Connected to MySQL database!');
// Release the connection when done
conn.release();
});
Using Promises
mysql2 supports promises for better async handling:
const mysql = require('mysql2/promise');
async function queryDatabase() {
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
password: 'yourpassword'
});
const [rows] = await connection.query('SELECT * FROM users');
console.log(rows);
await connection.end();
}
queryDatabase();
Common Errors and Solutions
If you get connection errors:
- Verify your MySQL server is running
- Check your username and password
- Ensure the database exists
For other Node.js module issues, see our guide on installing Socket.io.
Performance Tips
For better performance:
- Use connection pooling
- Enable prepared statements
- Handle errors properly
Learn more about performance in our Puppeteer installation guide.
Conclusion
The mysql2 module is essential for Node.js MySQL connectivity. It's fast, reliable, and easy to use.
Follow this guide to install and start using mysql2 in your projects today.