Category: java
MySQL driver package in your Node.js
Published on 26 May 2026
Explanation
Install the MySQL driver package in
your Node.js project using npm.
Code:
npm install mysql2
Explanation
Import the mysql2 package in your
Node.js application.
Code:
const mysql = require('mysql2');
Explanation
Create a MySQL connection using host,
username, password, and database name.
Code:
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'testdb'
});
Explanation
Connect Node.js application with
MySQL database.
Code:
connection.connect((err) => {
if (err) {
console.log('Connection Failed');
} else {
console.log('MySQL Connected');
}
});
Explanation
Execute SQL queries using the query()
method.
Code:
connection.query('SELECT * FROM users',
(err, results) => {
if (err) throw err;
console.log(results);
});