Node CRUD Application
Node CRUD Application
```bash
mkdir my-node-mysql-app
cd my-node-mysql-app
npm init -y
```
```bash
```
```
my-node-mysql-app/
├── node_modules/
├── package.json
├── package-lock.json
├── server.js
└── db.js
```
```js
user: 'your-username',
password: 'your-password',
database: 'your-database'
});
connection.connect((err) => {
if (err) {
return;
});
module.exports = connection;
```
Create a file named `server.js` to set up the Express server and define CRUD operations:
```js
const db = require('./db');
app.use(bodyParser.json());
const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';
return res.status(500).send(err);
});
});
if (err) {
return res.status(500).send(err);
res.status(200).send(results);
});
});
const { id } = req.params;
if (err) {
return res.status(500).send(err);
if (result.length === 0) {
res.status(200).send(result[0]);
});
});
// Update a record by id
app.put('/users/:id', (req, res) => {
const { id } = req.params;
if (err) {
return res.status(500).send(err);
if (result.affectedRows === 0) {
});
});
// Delete a record by id
const { id } = req.params;
if (err) {
return res.status(500).send(err);
if (result.affectedRows === 0) {
});
});
app.listen(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
USE your-database;
);
```
```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.