📖 Scenario: You are building a Node.js application that needs to connect to a MySQL database to store and retrieve user data.
🎯 Goal: Create a Node.js script that connects to a MySQL database using the mysql2 library.
📋 What You'll Learn
Create a connection configuration object with host, user, password, and database
Use the mysql2 library to create a connection
Connect to the database using the connection object
Close the connection properly after connecting
💡 Why This Matters
🌍 Real World
Connecting to a MySQL database is essential for many web applications to store and retrieve data.
💼 Career
Understanding how to connect to databases using Node.js and mysql2 is a common requirement for backend developers.
Progress0 / 4 steps
1
Create the connection configuration object
Create a constant called config that is an object with these exact properties and values: host: 'localhost', user: 'root', password: 'password123', and database: 'testdb'.
Node.js
Hint
Use an object literal with the exact keys and values for the database connection.
2
Import the mysql2 library and create a connection
Add a line to import mysql2 using import mysql from 'mysql2/promise'. Then create a constant called connection by calling await mysql.createConnection(config).
Node.js
Hint
Use ES module import syntax and the promise version of mysql2. Use await to create the connection.
3
Connect to the database and check connection
Add a try block where you await connection.connect() to establish the connection. Add a catch block to catch errors and throw them.
Node.js
Hint
Use a try/catch block to handle connection errors properly.
4
Close the database connection
Add a line to close the connection by calling await connection.end() after the try/catch block.
Node.js
Hint
Call connection.end() with await to close the connection cleanly.
Practice
(1/5)
1. What is the main purpose of the mysql2 package in Node.js?
easy
A. To create web servers
B. To connect and interact with MySQL databases
C. To style HTML pages
D. To manage file uploads
Solution
Step 1: Understand the role of mysql2
The mysql2 package is designed to help Node.js applications connect to and communicate with MySQL databases.
Step 2: Compare with other options
Options B, C, and D relate to other tasks like web servers, styling, or file uploads, which are not the purpose of mysql2.
Final Answer:
To connect and interact with MySQL databases -> Option B
Quick Check:
mysql2 = MySQL connection tool [OK]
Hint: Remember mysql2 is for database connection only [OK]
Common Mistakes:
Confusing mysql2 with web server packages
Thinking mysql2 styles web pages
Assuming mysql2 handles file uploads
2. Which of the following is the correct way to create a connection using mysql2 in Node.js?
easy
A. const connection = mysql2.newConnection('localhost', 'root', 'pass');
B. const connection = mysql2.connect({host: 'localhost', user: 'root'});
D. const connection = mysql2.open({host: 'localhost', user: 'root', password: 'pass'});
Solution
Step 1: Recall mysql2 connection syntax
The correct method to create a connection is createConnection with an object containing host, user, password, and database.
Step 2: Check each option
const connection = mysql2.createConnection({host: 'localhost', user: 'root', password: 'pass', database: 'test'}); uses createConnection with all required fields. Options A, B, and D use incorrect method names or missing parameters.
C. Incorrect method createConnection instead of connect
D. Missing database name in connection config
Solution
Step 1: Check connection config
While database name is missing, mysql2 allows connection without specifying database, so not a fatal error here.
Step 2: Analyze connection.end() placement
connection.end() is called immediately after connect(), which may close connection before it is established or query runs.
Final Answer:
Using connection.end() before connect callback -> Option A
Quick Check:
Close connection only after queries finish [OK]
Hint: Call connection.end() after queries complete [OK]
Common Mistakes:
Calling connection.end() too early
Assuming database is always required
Confusing createConnection with connect method
5. You want to run a query to select all users from a MySQL database using mysql2. Which code snippet correctly handles the connection, query, and closing the connection?
hard
A. const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass', database:'test'});
conn.connect(err => {
if (err) throw err;
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
conn.end();
});
});
B. const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass', database:'test'});
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
});
conn.end();
C. const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass', database:'test'});
conn.end();
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
});
D. const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass'});
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
conn.end();
});
Solution
Step 1: Properly connect before querying
const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass', database:'test'});
conn.connect(err => {
if (err) throw err;
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
conn.end();
});
}); calls connect first, ensuring connection is ready before running the query.
Step 2: Close connection after query completes
const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass', database:'test'});
conn.connect(err => {
if (err) throw err;
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
conn.end();
});
}); calls conn.end() inside the query callback, so connection closes only after query finishes.
Step 3: Check other options
const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass', database:'test'});
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
});
conn.end(); calls conn.end() immediately after query, which may close connection too soon. const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass', database:'test'});
conn.end();
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
}); closes connection before query. const mysql = require('mysql2');
const conn = mysql.createConnection({host:'localhost', user:'root', password:'pass'});
conn.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
console.log(results);
conn.end();
}); misses database in config.
Final Answer:
Correctly connects, queries, and closes connection in proper sequence using nested callbacks -> Option A
Quick Check:
Connect first, query next, then close connection [OK]
Hint: Connect first, query inside callback, then close connection [OK]
Common Mistakes:
Closing connection before query finishes
Not waiting for connect callback before querying
Omitting database in connection config
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.