Using MySQL in Node.js

CK CK 3788 
Created at  
480 0 0

To use MySQL in a Node.js application, you'll need to install the mysql package (or mysql2 for improved performance and additional features). Below is a step-by-step guide on how to set up and interact with a MySQL database using Node.js.

 

Step 1: Install MySQL and Node.js MySQL Module

  1. Ensure MySQL is installed and running on your machine or server.
  2. Install the MySQL package for Node.js:

    npm install mysql
    

    Alternatively, you can install mysql2:

    npm install mysql2
    

 

Step 2: Create a MySQL Database and Table

Before interacting with the database, you need a database and a table. You can create them using MySQL Workbench, phpMyAdmin, or the MySQL command line.

CREATE DATABASE nodejs_db;

USE nodejs_db;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    age INT
);

 

Step 3: Connect to the MySQL Database from Node.js

Create a new JavaScript file (e.g., app.js) and set up the connection to the MySQL database.

File: app.js

const mysql = require('mysql');

// Create a connection to the database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root', // Your MySQL username
  password: 'password', // Your MySQL password
  database: 'nodejs_db' // Name of your database
});

// Connect to the database
connection.connect((err) => {
  if (err) {
    console.error('Error connecting to the database:', err.stack);
    return;
  }
  console.log('Connected to the database as ID', connection.threadId);
});

 

Step 4: Perform CRUD Operations

4.1 Insert Data

File: app.js (continued)

// Insert a new user into the database
const user = { name: 'John Doe', email: 'john@example.com', age: 30 };
const query = 'INSERT INTO users SET ?';

connection.query(query, user, (err, result) => {
  if (err) {
    console.error('Error inserting data:', err.stack);
    return;
  }
  console.log('Data inserted, ID:', result.insertId);
});

 

4.2 Query Data

File: app.js (continued)

// Retrieve users from the database
connection.query('SELECT * FROM users', (err, results) => {
  if (err) {
    console.error('Error fetching data:', err.stack);
    return;
  }
  console.log('Users:', results);
});

 

4.3 Update Data

File: app.js (continued)

// Update a user's age
const newAge = 31;
const userId = 1;
connection.query('UPDATE users SET age = ? WHERE id = ?', [newAge, userId], (err, result) => {
  if (err) {
    console.error('Error updating data:', err.stack);
    return;
  }
  console.log('Rows affected:', result.affectedRows);
});

 

4.4 Delete Data

File: app.js (continued)

// Delete a user from the database
connection.query('DELETE FROM users WHERE id = ?', [userId], (err, result) => {
  if (err) {
    console.error('Error deleting data:', err.stack);
    return;
  }
  console.log('Rows deleted:', result.affectedRows);
});

 

Step 5: Close the Connection

After performing database operations, it's good practice to close the connection.

File: app.js (continued)

// Close the database connection
connection.end((err) => {
  if (err) {
    console.error('Error closing the connection:', err.stack);
    return;
  }
  console.log('Database connection closed.');
});

 

Step 6: Run the Application

To execute the script, run:

node app.js

Notes:

  1. Error Handling: Ensure you handle errors properly in a production environment. The examples provided log errors to the console, but in real-world applications, you'd handle them more robustly.
  2. Connection Pooling: For better performance in larger applications, consider using connection pooling rather than creating a new connection for each request.
  3. Prepared Statements: For better security, especially to prevent SQL injection attacks, use prepared statements or parameterized queries as shown in the examples above (e.g., UPDATE and DELETE queries).
  4. mysql2: If using mysql2, the syntax is almost identical, but it offers better performance and additional features, such as support for Promises and async/await.
Tags MySQL Node.js MySQL Facebook X
Comments 0
Similar posts
  1. Rust code example to access MySQL
    1,098
  2. Change MySQL port number for security purpose
    815
  3. The Ultimate Data Engineering Roadmap
    1,073
  4. How do I create a user account in read-only mode at MySQL?
    3,321
  5. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  6. Stateful Databases: A Deep Dive with Cassandra & TiDB
    189
  7. How to set AUTO_INCREMENT ID in mySQL ?
    607
  1. Get client IP address and user agent in Node.js
    1,530
  2. forEach method in JavaScript when working with arrays
    665
  3. CRC32B function code in Javascript
    1,839
  4. Node.js-based Web Server supporting multiple path
    598
  5. A simple Javascript class example with static method for Node.js
    660
  6. Setting a Common Path for require() in Node.js
    993
  7. Import all JS files in a specific folder for Node.js programming
    1,724
  8. A simple example to access a PostgreSQL database in Node.js
    1,100
  9. Node.js code example to access Google BigQuery
    1,181
  10. Investigation on package.js for Node.js source code
    819
  11. A Node.js script that checks if a module is installed before requiring it
    770
  12. Worker Threads and Mutual Exclusion in Node.js
    461
  13. Using a module in the external class itself without creating an instance in Node.js
    349
  14. Node.js external modules
    430
  15. Multi-threaded Web Server based in Node.js
    864
  16. A basic HTTP server based in Node.js
    538
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,018
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. What is RedisVL?
    109
  14. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  15. TPU & GPU Cluster Management Tools
    245
  16. The Concept of Scaffolding in AI Agents
    234
  17. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  18. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  19. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  20. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  21. Machine Learning: Training vs. Ranking
    222
  22. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  23. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  24. Designing a Data Curation System Around a Vector Database
    221
  25. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  26. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  27. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  28. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  29. Understanding Data Lineage
    262
  30. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    167