Node curd application using MYSQL

In this example, we will learn the node   CURD   application. Using  MYSQL database. 

          1.  Create  rest  Client 

          2.  Create a database  connection  

          3.  Html  page 

Rest   client 


const axios = require('axios');

// CREATE operation
const createData = async (data) => {
  try {
    const response = await axios.post('http://bhrikutisoft.com/data', data);
    console.log('Data created successfully');
    console.log(response.data); // Display the created data
  } catch (error) {
    console.error('Error creating data: ', error.response.data);
  }
};

// READ operation
const readData = async () => {
  try {
    const response = await axios.get('http://bhrikutisoft.com/data');
    console.log('Data retrieved successfully');
    console.log(response.data); // Display the retrieved data
  } catch (error) {
    console.error('Error reading data: ', error.response.data);
  }
};

// UPDATE operation
const updateData = async (id, data) => {
  try {
    const response = await axios.put(`http://bhrikutisoft.com/data/${id}`, data);
    console.log('Data updated successfully');
    console.log(response.data); // Display the updated data
  } catch (error) {
    console.error('Error updating data: ', error.response.data);
  }
};

// DELETE operation
const deleteData = async (id) => {
  try {
    const response = await axios.delete(`http://bhrikutisoft.com/data/${id}`);
    console.log('Data deleted successfully');
    console.log(response.data); // Display the deleted data
  } catch (error) {
    console.error('Error deleting data: ', error.response.data);
  }
};

// Call the CRUD functions
const dataToCreate = { name: 'John Doe', age: 25 };
createData(dataToCreate);

readData();

const dataToUpdate = { name: 'Jane Smith', age: 30 };
updateData(1, dataToUpdate);

deleteData(1);



Database  Connection .


  const mysql = require('mysql');

// Create a connection to the MySQL database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database_name'
});

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

// CREATE operation
const createData = () => {
  const insertQuery = 'INSERT INTO your_table_name (column1, column2) VALUES (?, ?)';
  const data = ['value1', 'value2'];

  connection.query(insertQuery, data, (error, results) => {
    if (error) {
      console.error('Error creating data: ', error);
      return;
    }
    console.log('Data created successfully');
  });
};

// READ operation
const readData = () => {
  const selectQuery = 'SELECT * FROM your_table_name';

  connection.query(selectQuery, (error, results) => {
    if (error) {
      console.error('Error reading data: ', error);
      return;
    }
    console.log('Data retrieved successfully');
    console.log(results); // Display the retrieved data
  });
};

// UPDATE operation
const updateData = () => {
  const updateQuery = 'UPDATE your_table_name SET column1 = ? WHERE id = ?';
  const data = ['new_value', 1];

  connection.query(updateQuery, data, (error, results) => {
    if (error) {
      console.error('Error updating data: ', error);
      return;
    }
    console.log('Data updated successfully');
  });
};

// DELETE operation
const deleteData = () => {
  const deleteQuery = 'DELETE FROM your_table_name WHERE id = ?';
  const id = 1;

  connection.query(deleteQuery, id, (error, results) => {
    if (error) {
      console.error('Error deleting data: ', error);
      return;
    }
    console.log('Data deleted successfully');
  });
};




Html page

<!DOCTYPE html>
<html>
<head>
  <title>CRUD Page</title>
</head>
<body>
  <h1>CRUD Page</h1>
  
  <!-- Create Form -->
  <h2>Create</h2>
  <form action="/create" method="POST"  id=”createdata”>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br><br>
    
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br><br>
    
    <input type="submit" value="Create">
  </form>
  
  <!-- Read Data -->
  <h2>Read</h2>
  <table>
    <tr>
      <th>Name</th>
      <th>Email</th>
    </tr>
    <!-- Replace this section with server-side code to fetch and display data -->
    <tr>
      <td>John Doe</td>
      <td>johndoe@example.com</td>
    </tr>
  </table>
  
  <!-- Update Form -->
  <h2>Update</h2>
  <form action="/update" method="POST"  id=”updatedata”>
    <label for="id">ID:</label>
    <input type="text" id="id" name="id" required><br><br>
    
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br><br>
    
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required><br><br>
    
    <input type="submit" value="Update">
  </form>
  
  <!-- Delete Form -->
  <h2>Delete</h2>
  <form action="/delete" method="POST"   id=”deldata”>
    <label for="id">ID:</label>
    <input type="text" id="id" name="id" required><br><br>
    
    <input type="submit" value="Delete">
  </form>
  
  <script>
 const thisForm = document.getElementById('createdata');
thisForm.addEventListener('submit', async function (e) {
    e.preventDefault();
    const formData = new FormData(thisForm).entries()
    const response = await fetch(' http://bhrikutisoft.com/data', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(Object.fromEntries(formData))
    });

    const result = await response.json();
    console.log(result)
});
const thisForm = document.getElementById('deldata');
thisForm.addEventListener('submit', async function (e) {
    e.preventDefault();
    const formData = new FormData(thisForm).entries()
    const response = await fetch(' http://bhrikutisoft.com/data/${id}, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(Object.fromEntries(formData))
    });

    const result = await response.json();
    console.log(result)
});
const thisForm = document.getElementById('updatedata');
thisForm.addEventListener('submit', async function (e) {
    e.preventDefault();
    const formData = new FormData(thisForm).entries()
    const response = await fetch(' http://bhrikutisoft.com/data/${id}, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(Object.fromEntries(formData))
    });

    const result = await response.json();
    console.log(result)
});

  </script>
</body>
</html>

  This code has not been tested on my computer.



Node curd application using MYSQL  Node curd  application using  MYSQL Reviewed by Mukesh Jha on 8:41 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.