CRUD Operations with Node JS, Express, and MySQL #programming #javascript #nodejs #backend

Posted by


In this tutorial, we will learn how to perform CRUD operations using Node.js, Express, and MySQL. CRUD stands for Create, Read, Update, and Delete, which are the basic operations that can be performed on a database.

Before we begin, make sure you have Node.js and MySQL installed on your system. You can download Node.js from the official website (https://nodejs.org) and MySQL from the official website (https://www.mysql.com).

Let’s start by creating a new Node.js project. Open your terminal and navigate to the directory where you want to create your project. Run the following command to create a new Node.js project:

npm init -y

This will create a new package.json file in your project directory. Next, we need to install the required dependencies. Run the following command to install express and mysql:

npm install express mysql

Next, create a new file called app.js in your project directory. This will be our main application file. Open app.js and add the following code to set up our Express application and connect to the MySQL database:

const express = require('express');
const mysql = require('mysql');

const app = express();

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

connection.connect((error) => {
  if (error) {
    console.error('Error connecting to MySQL: ' + error.stack);
    return;
  }

  console.log('Connected to MySQL as id ' + connection.threadId);
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

Replace localhost, root, password, and mydatabase with your MySQL server details. This code will create a connection to the MySQL database and start an Express server on port 3000.

Now let’s implement the CRUD operations. We will create routes for creating, reading, updating, and deleting records in a users table. Add the following routes to app.js:

app.get('/users', (req, res) => {
  connection.query('SELECT * FROM users', (error, results) => {
    if (error) {
      res.status(500).json({ error: error.message });
      return;
    }

    res.json(results);
  });
});

app.post('/users', (req, res) => {
  const { name, email } = req.body;

  connection.query('INSERT INTO users (name, email) VALUES (?, ?)', [name, email], (error, result) => {
    if (error) {
      res.status(500).json({ error: error.message });
      return;
    }

    res.json({ message: 'User created successfully', id: result.insertId });
  });
});

app.put('/users/:id', (req, res) => {
  const { name, email } = req.body;
  const { id } = req.params;

  connection.query('UPDATE users SET name = ?, email = ? WHERE id = ?', [name, email, id], (error, result) => {
    if (error) {
      res.status(500).json({ error: error.message });
      return;
    }

    res.json({ message: 'User updated successfully' });
  });
});

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

  connection.query('DELETE FROM users WHERE id = ?', [id], (error, result) => {
    if (error) {
      res.status(500).json({ error: error.message });
      return;
    }

    res.json({ message: 'User deleted successfully' });
  });
});

These routes will allow us to perform CRUD operations on the users table. The GET route fetches all users from the database, the POST route creates a new user, the PUT route updates an existing user, and the DELETE route deletes a user by their ID.

Finally, start your Express server by running the following command in the terminal:

node app.js

You can now test your CRUD operations using a tool like Postman or curl. Make sure to replace users with the appropriate endpoint for each operation (e.g., /users, /users/:id, etc.).

That’s it! You have successfully implemented CRUD operations using Node.js, Express, and MySQL. Happy coding!

0 0 votes
Article Rating

Leave a Reply

34 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Agucho_
7 days ago

Hola, no se por que cuando intento de mostrar la primera interfaz, me tira error : Error: Failed to lookup view "index" in views directory. Revise todo el video, el código y no tengo nada diferente a lo que tu tienes y me tira el error. en el minuto 26:21. Que lo puede estar causando?

@danielbaron8711
7 days ago

Tengo un problema con el navbar, no aparece

@luiszapata563
7 days ago

Muy bueno, muy bien explicado, muchas gracias Luis Angel por tu humildad para explicar. Un saludo desde Colombia

@jesusgregoriosola5871
7 days ago

Agradezco mucho su trabajo por haberlo hecho tan completo y didáctico. Mil gracias Profesor y cordiales saludos.

@FBI._.1908
7 days ago

Gran tributo a programacionATS ;-;

@gianvallejos7631
7 days ago

Hermoso! Muchas gracias 🙌

@josebylogic
7 days ago

Hola, gracias y felicitaciones por tu trabajo!!! se me presenta el siguiente error al renderizar la interface con hbs. Alguna sugerencia? va parte del mensaje devuelto en el navegador/consola: Error: Failed to lookup view "index" in views directory "C:Usersjosejsourcerepospruebasrc"

at Function.render (C:Usersjosejsourcerepospruebanode_modulesexpresslibapplication.js:597:17)

at ServerResponse.render (C:Usersjosejsourcerepospruebanode_modulesexpresslibresponse.js:1048:7)

at file:///C:/Users/josej/source/repos/prueba/src/index.js:51:9

@alexfrias7979
7 days ago

Gracias Crack!!!

@roberthbarre
7 days ago

hice todo, modifque a mi conveniencia y segun lo que yo queria, me da error cuando hago npm run build para luego hacer el deploy y subir a firebase, sabes por qué?, psdt Exelente video

@ceb-unlockmaster
7 days ago

Cordial saludo ya programe todo pero me sale un error url: 'file:///C:/Users/Unlock/Desktop/SEGURIDAD-ELITE/node_modules/mysql/promise'
} y este node:internal/modules/esm/resolve:265
throw new ERR_MODULE_NOT_FOUND( pero ese error me sale cada vez que importo este archivo import personasRoutes from'./routes/supervisores.routes.js'

@arielfuentes3775
7 days ago

Como lo pondrías en un sitio estático? Por ejemplo netyfly, la base de datos la conectarias a firebase?

@arielfuentes3775
7 days ago

Esa frase es de Alejandro Taboada (Programación ATS). Murió muy joven, espero menciones la frase a manera de homenaje

@Reaperdip
7 days ago

21:10 o tambien usen Alt + z

@beticohernandez9536
7 days ago

Buen video.

@ZerGamerAP
7 days ago

De casualidad no lo tendrá conectado a angular? x'd

@ZerGamerAP
7 days ago

34:47 – Listando y creando empleados

@sinsin5556
7 days ago

Felicitaciones! por compartir tu conocimiento. El tutorial bien explicado, Muchas Gracias.

@enelanonymatus5634
7 days ago

Buen video, ¿cuál es el tema de tu VS?

@miyagui527
7 days ago

GENIAL. amigo es una extensión la que usas para que te aparezca la sugerencia de la palabra que vas a utilizar ?

@nahuelmasajnik1831
7 days ago

Es orientado a microservicios?

34
0
Would love your thoughts, please comment.x
()
x