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

SQL_MONGO_CODE

Uploaded by

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

SQL_MONGO_CODE

Uploaded by

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

DBMS

Frontend:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<title>User Management</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body class="container mt-5">
<h2>User Management</h2>

<form id="userForm" class="mb-4">


<input type="hidden" id="userId">
<div class="form-group">
<label>Name</label>
<input type="text" id="name" class="form-control" required>
</div>
<div class="form-group">
<label>Age</label>
<input type="number" id="age" class="form-control" required>
</div>
<div class="form-group">
<label>Mobile No</label>
<input type="text" id="mob_no" class="form-control" required>
</div>
<div class="form-group">
<label>Address</label>
<input type="text" id="address" class="form-control" required>
</div>
<button type="button" onclick="insertUser()" class="btn btn-primary">Insert</button>
<button type="button" onclick="updateUser()" class="btn btn-warning">Update</button>
<button type="button" onclick="deleteUser()" class="btn btn-danger">Delete</button>
<button type="button" onclick="fetchUsers()" class="btn btn-secondary">Refresh</button>
</form>

<table class="table table-bordered" id="userTable">


<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Mobile No</th>
<th>Address</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
const userTableBody = document.querySelector('#userTable tbody');

function fetchUsers() {
axios.get('http://localhost:3000/users')
.then(response => {
userTableBody.innerHTML = '';
response.data.forEach(user => {
userTableBody.innerHTML += `
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
<td>${user.mob_no}</td>
<td>${user.address}</td>
<td>
<button class="btn btn-info" onclick="populateForm(${JSON.stringify(user)})">Edit</button>
</td>
</tr>
`;
});
});
}
function populateForm(user) {
document.getElementById('userId').value = user.id;
document.getElementById('name').value = user.name;
document.getElementById('age').value = user.age;
document.getElementById('mob_no').value = user.mob_no;
document.getElementById('address').value = user.address;
}
function insertUser() {
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
const mob_no = document.getElementById('mob_no').value;
const address = document.getElementById('address').value;
axios.post('http://localhost:3000/users', { name, age, mob_no, address })
.then(() => {
fetchUsers();
document.getElementById('userForm').reset();
});
}
function updateUser() {
const id = document.getElementById('userId').value;
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
const mob_no = document.getElementById('mob_no').value;
const address = document.getElementById('address').value;
axios.put(`http://localhost:3000/users/${id}`, { name, age, mob_no, address })
.then(() => {
fetchUsers();
document.getElementById('userForm').reset();
});
}
function deleteUser() {
const id = document.getElementById('userId').value;

axios.delete(`http://localhost:3000/users/${id}`)
.then(() => {
fetchUsers();
document.getElementById('userForm').reset();
});
}
fetchUsers();
</script>
</body>
</html>

Interface:
Backend MySQL:

const express = require('express');


const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'user123',
database: 'DPCOE'
});
db.connect(err => {
if (err) throw err;
console.log('MySQL Connected...');
});
app.get('/users', (req, res) => {
db.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
res.json(results);
});
});
app.post('/users', (req, res) => {
const { name, age, mob_no, address } = req.body;
db.query('INSERT INTO users (name, age, mob_no, address) VALUES (?, ?, ?, ?)', [name, age, mob_no, address], (err) => {
if (err) throw err;
res.sendStatus(201);
});
});
app.put('/users/:id', (req, res) => {
const { id } = req.params;
const { name, age, mob_no, address } = req.body;
db.query('UPDATE users SET name=?, age=?, mob_no=?, address=? WHERE id=?', [name, age, mob_no, address, id], (err) => {
if (err) throw err;
res.sendStatus(200);
});
});
app.delete('/users/:id', (req, res) => {
const { id } = req.params;
db.query('DELETE FROM users WHERE id=?', [id], (err) => {
if (err) throw err;
res.sendStatus(204);
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

Result:
Backend MongoDB:

const express = require('express');


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

const app = express();


const PORT = 3000;

app.use(cors());
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost:27017/DPCOE', { useNewUrlParser: true, useUnifiedTopology: true })


.then(() => console.log('MongoDB Connected...'))
.catch(err => console.error('MongoDB connection error:', err));

const userSchema = new mongoose.Schema({


name: String,
age: Number,
mob_no: String,
address: String
});
const User = mongoose.model('User', userSchema);

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


try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).send(err);
}
});

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


const { name, age, mob_no, address } = req.body;
const user = new User({ name, age, mob_no, address });

try {
await user.save();
res.sendStatus(201);
} catch (err) {
res.status(500).send(err);
}
});

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


const { id } = req.params;
const { name, age, mob_no, address } = req.body;

try {
await User.findByIdAndUpdate(id, { name, age, mob_no, address });
res.sendStatus(200);
} catch (err) {
res.status(500).send(err);
}
});

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


const { id } = req.params;

try {
await User.findByIdAndDelete(id);
res.sendStatus(204);
} catch (err) {
res.status(500).send(err);
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
MongoDB Result:

You might also like