0
0
Node.jsframework~10 mins

MySQL connection with mysql2 in Node.js - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - MySQL connection with mysql2
Import mysql2 module
Create connection config
Call mysql.createConnection()
Connect to MySQL server
Check for connection error
Handle error
Use connection for queries
Close connection when done
This flow shows how to import mysql2, create a connection, handle errors, and use the connection for queries.
Execution Sample
Node.js
import mysql from 'mysql2';

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'pass',
  database: 'testdb'
});

connection.connect(err => {
  if (err) {
    console.error('Connection error:', err);
    return;
  }
  console.log('Connected!');
  connection.end();
});
This code connects to a MySQL database using mysql2, logs success or error, then closes the connection.
Execution Table
StepActionEvaluationResult
1Import mysql2 moduleModule importedmysql object available
2Create connection configConfig object created{host:'localhost', user:'root', password:'pass', database:'testdb'}
3Call mysql.createConnection()Connection object createdconnection object ready
4Call connection.connect()Attempt to connect to MySQL serverConnecting...
5Check for error in callbackError? (err is null or error object)No error, err=null
6Log 'Connected!'Console outputConnected!
7Call connection.end()Close connectionConnection closed
💡 Connection established successfully, then closed.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
mysqlundefinedmysql module importedmysql module importedmysql module importedmysql module importedmysql module imported
connectionundefinedundefinedconnection object createdconnection object connectingconnection object connectedconnection object closed
errundefinedundefinedundefinedundefinednull (no error)null
Key Moments - 3 Insights
Why do we check if 'err' exists in the connect callback?
Because the connection might fail. Checking 'err' (see step 5 in execution_table) lets us handle connection errors gracefully instead of crashing.
What happens if we forget to call connection.end()?
The connection stays open, which can cause resource leaks. Step 7 shows closing the connection to free resources.
Is the connection synchronous or asynchronous?
Connecting is asynchronous. The connect() method takes a callback that runs after connection attempt (step 4 and 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is the value of 'err' if connection succeeds?
AAn error object
Bnull
Cundefined
Dtrue
💡 Hint
Check the 'Evaluation' and 'Result' columns at step 5 in execution_table.
At which step is the connection object created?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Action' column for when mysql.createConnection() is called.
If the password is wrong, what changes in the execution_table?
AStep 5 'err' will be an error object instead of null
BStep 3 connection object is not created
CStep 7 connection.end() is called earlier
DStep 1 import fails
💡 Hint
Think about what happens if connection fails at step 5.
Concept Snapshot
Import mysql2 module
Create connection with mysql.createConnection(config)
Call connection.connect(callback) to connect asynchronously
Check error in callback to handle failures
Use connection for queries
Call connection.end() to close connection
Full Transcript
This example shows how to connect to a MySQL database using the mysql2 library in Node.js. First, we import the mysql2 module. Then, we create a connection object with the database details like host, user, password, and database name. We call connection.connect() with a callback to start connecting asynchronously. Inside the callback, we check if there is an error. If no error, we log 'Connected!'. Finally, we close the connection with connection.end() to free resources. This flow ensures safe and proper connection handling.