0% found this document useful (0 votes)
28 views

Node CRUD Application

Uploaded by

Tariq Rashid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Node CRUD Application

Uploaded by

Tariq Rashid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Sure! I can help you create a Node.

js project to connect to a MySQL database and perform CRUD (Create, Read,


Update, Delete) operations. Here is a step-by-step guide:

### Step 1: Set up your Node.js project

1. **Initialize a new Node.js project:**

```bash

mkdir my-node-mysql-app

cd my-node-mysql-app

npm init -y

```

2. **Install necessary packages:**

```bash

npm install express mysql2

```

### Step 2: Create the project structure

Your project directory should look like this:

```

my-node-mysql-app/

├── node_modules/

├── package.json

├── package-lock.json

├── server.js

└── db.js

```

### Step 3: Create `db.js` to handle MySQL connection

Create a file named `db.js` to manage the database connection:

```js

const mysql = require('mysql2');

const connection = mysql.createConnection({


host: 'localhost',

user: 'your-username',

password: 'your-password',

database: 'your-database'

});

connection.connect((err) => {

if (err) {

console.error('Error connecting to MySQL:', err);

return;

console.log('Connected to MySQL database');

});

module.exports = connection;

```

### Step 4: Set up the server and CRUD routes in `server.js`

Create a file named `server.js` to set up the Express server and define CRUD operations:

```js

const express = require('express');

const bodyParser = require('body-parser');

const db = require('./db');

const app = express();

const port = 3000;

app.use(bodyParser.json());

// Create a new record

app.post('/users', (req, res) => {

const { name, email } = req.body;

const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';

db.query(sql, [name, email], (err, result) => {


if (err) {

return res.status(500).send(err);

res.status(201).send({ id: result.insertId, name, email });

});

});

// Read all records

app.get('/users', (req, res) => {

const sql = 'SELECT * FROM users';

db.query(sql, (err, results) => {

if (err) {

return res.status(500).send(err);

res.status(200).send(results);

});

});

// Read a single record by id

app.get('/users/:id', (req, res) => {

const { id } = req.params;

const sql = 'SELECT * FROM users WHERE id = ?';

db.query(sql, [id], (err, result) => {

if (err) {

return res.status(500).send(err);

if (result.length === 0) {

return res.status(404).send({ message: 'User not found' });

res.status(200).send(result[0]);

});

});

// Update a record by id
app.put('/users/:id', (req, res) => {

const { id } = req.params;

const { name, email } = req.body;

const sql = 'UPDATE users SET name = ?, email = ? WHERE id = ?';

db.query(sql, [name, email, id], (err, result) => {

if (err) {

return res.status(500).send(err);

if (result.affectedRows === 0) {

return res.status(404).send({ message: 'User not found' });

res.status(200).send({ id, name, email });

});

});

// Delete a record by id

app.delete('/users/:id', (req, res) => {

const { id } = req.params;

const sql = 'DELETE FROM users WHERE id = ?';

db.query(sql, [id], (err, result) => {

if (err) {

return res.status(500).send(err);

if (result.affectedRows === 0) {

return res.status(404).send({ message: 'User not found' });

res.status(200).send({ message: 'User deleted' });

});

});

app.listen(port, () => {

console.log(`Server is running on port ${port}`);

});

```
### Step 5: Set up the MySQL database

Make sure you have a MySQL server running and create a database and table for the example:

```sql

CREATE DATABASE your-database;

USE your-database;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(255) NOT NULL,

email VARCHAR(255) NOT NULL

);

```

### Step 6: Run the server

Start your Node.js server by running:

```bash

node server.js

```

Your server should now be running and listening on `http://localhost:3000`. You can use tools like Postman to test
the CRUD endpoints.

### Summary

You've set up a basic Node.js project that connects to a MySQL database and provides CRUD operations. You can
extend this example by adding more features, handling errors more gracefully, and using environment variables to
store sensitive information like database credentials.

You might also like