If you're using Windows and want to integrate a MySQL database with a Node.
js
backend, the process is quite similar to what was described earlier. Below is a
step-by-step guide tailored for Windows users.
Step-by-Step Guide for Windows
1. Install Required Software
Install Node.js: Download and install Node.js from the official Node.js website.
Make sure to check the option to install npm (Node Package Manager) during
installation.
Install MySQL: Download and install MySQL from the MySQL Community Server. During
installation, remember the root password you set.
2. Set Up Your Project
Open Command Prompt:
Press Win + R, type cmd, and hit Enter.
Create a New Project Directory:
bash
Verify
Open In Editor
Edit
Copy code
mkdir my_project
cd my_project
Initialize a New Node.js Project:
bash
Verify
Open In Editor
Edit
Copy code
npm init -y
Install Required Packages: For MySQL, install the mysql and express packages:
bash
Verify
Open In Editor
Edit
Copy code
npm install mysql express
3. Create Your Database and Tables
Open MySQL Command Line:
Open the MySQL Command Line Client from your Start menu.
Log in using the root username and the password you set during installation.
Create Database and Tables: Execute the following SQL commands to create your
database and tables:
sql
Verify
Open In Editor
Edit
Copy code
CREATE DATABASE task_management;
USE task_management;
CREATE TABLE Users (
UserID INT AUTO_INCREMENT,
Username VARCHAR(50) NOT NULL UNIQUE,
PasswordHash VARCHAR(255) NOT NULL,
Email VARCHAR(100) NOT NULL UNIQUE,
CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (User ID)
);
CREATE TABLE Tasks (
TaskID INT AUTO_INCREMENT,
UserID INT NOT NULL,
TaskName VARCHAR(100) NOT NULL,
IsCompleted BOOLEAN DEFAULT FALSE,
CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (TaskID),
FOREIGN KEY (User ID) REFERENCES Users(UserID) ON DELETE CASCADE
);
4. Set Up Database Connection
Create a file named db.js in your project directory to handle the database
connection:
javascript
Verify
Open In Editor
Edit
Copy code
// db.js
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root', // or your MySQL username
password: 'your_password', // replace with your MySQL password
database: 'task_management'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err);
return;
}
console.log('Connected to the database!');
});
module.exports = connection;
5. Set Up Express Server
Create a file named app.js in your project directory to set up your Express server:
javascript
Verify
Open In Editor
Edit
Copy code
// app.js
const express = require('express');
const db = require('./db'); // Import the database connection
const app = express();
const PORT = 3000;
app.use(express.json()); // Middleware to parse JSON requests
// Example route to get all users
app.get('/users', (req, res) => {
db.query('SELECT * FROM Users', (err, results) => {
if (err) {
return res.status(500).json({ error: 'Database query failed' });
}
res.json(results);
});
});
// Add a new user
app.post('/users', (req, res) => {
const { Username, PasswordHash, Email } = req.body;
const query = 'INSERT INTO Users (Username, PasswordHash, Email) VALUES
(?, ?, ?)';
db.query(query, [Username, PasswordHash, Email], (err, results) => {
if (err) {
return res.status(500).json({ error: 'Failed to add user' });
}
res.status(201).json({ id: results.insertId, Username });
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
6. Run Your Application
Open a New Command Prompt:
Navigate to your project directory:
bash
Verify
Open In Editor
Edit
Copy code
cd path\to\your\my_project
Start the Server:
bash
Verify
Open In Editor
Edit
Copy code
node app.js
Test Your API: Use tools like Postman or curl to test your API endpoints. For
example, you can test the GET /users endpoint to retrieve all users.