Getting Started with Node.js and MySQL: A Comprehensive Guide

Getting Started with Node.js and MySQL

This guide provides a comprehensive introduction to using Node.js with MySQL, a popular relational database. It covers the essential steps to set up a Node.js application that interacts with a MySQL database.

Key Concepts

  • Node.js: A JavaScript runtime built on Chrome's V8 engine that allows you to run JavaScript on the server side.
  • MySQL: An open-source relational database management system that uses structured query language (SQL) for accessing and managing data.

Setting Up the Environment

  1. Install Node.js
  2. Install MySQL
  3. Create a Database
    • Use a MySQL client (like MySQL Workbench) to create a database.
    • Example SQL command to create a database:
CREATE DATABASE mydb;

Creating a Node.js Application

  1. Initialize a Node.js Project
  2. Install MySQL Driver

Install the MySQL driver for Node.js using npm:

npm install mysql

Use the command line to create a new project folder and initialize it:

mkdir my-node-app
cd my-node-app
npm init -y

Connecting to MySQL Database

Create a file (e.g., app.js) and set up the connection:

const mysql = require('mysql');

// Create a connection to the database
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'yourusername',
    password: 'yourpassword',
    database: 'mydb'
});

// Connect to the database
connection.connect((err) => {
    if (err) throw err;
    console.log('Connected to MySQL database!');
});

Performing Database Operations

Retrieving Data

const selectQuery = 'SELECT * FROM users';

connection.query(selectQuery, (err, results) => {
    if (err) throw err;
    console.log('User data:', results);
});

Inserting Data

const insertQuery = `INSERT INTO users (name, email) VALUES ('John Doe', '[email protected]')`;

connection.query(insertQuery, (err, result) => {
    if (err) throw err;
    console.log('Data inserted:', result.insertId);
});

Creating a Table

const createTableQuery = `CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL
)`;

connection.query(createTableQuery, (err, result) => {
    if (err) throw err;
    console.log('Table created:', result);
});

Conclusion

This guide has covered the basics of setting up a Node.js application to interact with a MySQL database. By following these steps, you can create databases, tables, and perform various CRUD (Create, Read, Update, Delete) operations using Node.js and MySQL.