Node.js 數(shù)據(jù)庫 CRUD 項目示例詳解(完美解決方案)
希望使用Nodejs操作數(shù)據(jù)庫做CRUD,用deepseek實戰(zhàn)搜索“使用Nodejs對數(shù)據(jù)庫表做CRUD的項目例子”,找到了解決方案,如下圖所示:

項目結構
nodejs-crud-example/ ├── config/ │ └── db.js # 數(shù)據(jù)庫連接配置 ├── controllers/ │ └── userController.js # 業(yè)務邏輯 ├── models/ │ └── userModel.js # 數(shù)據(jù)庫操作 ├── routes/ │ └── userRoutes.js # 路由定義 ├── app.js # 應用入口 ├── package.json └── README.md
1. 初始化項目
mkdir nodejs-crud-example cd nodejs-crud-example npm init -y npm install express mysql2 body-parser cors

2. 配置數(shù)據(jù)庫連接 (config/db.js)
const mysql = require('mysql2/promise');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'yourpassword',
database: 'testdb',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
module.exports = pool;3. 創(chuàng)建模型 (models/userModel.js)
const pool = require('../config/db');
class User {
static async getAll() {
const [rows] = await pool.query('SELECT * FROM users');
return rows;
}
static async getById(id) {
const [rows] = await pool.query('SELECT * FROM users WHERE id = ?', [id]);
return rows[0];
}
static async create(name, email) {
const [result] = await pool.query(
'INSERT INTO users (name, email) VALUES (?, ?)',
[name, email]
);
return { id: result.insertId, name, email };
}
static async update(id, name, email) {
await pool.query(
'UPDATE users SET name = ?, email = ? WHERE id = ?',
[name, email, id]
);
return { id, name, email };
}
static async delete(id) {
await pool.query('DELETE FROM users WHERE id = ?', [id]);
return true;
}
}
module.exports = User;4. 創(chuàng)建控制器 (controllers/userController.js)
const User = require('../models/userModel');
exports.getAllUsers = async (req, res) => {
try {
const users = await User.getAll();
res.json(users);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
exports.getUser = async (req, res) => {
try {
const user = await User.getById(req.params.id);
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
} catch (err) {
res.status(500).json({ message: err.message });
}
};
exports.createUser = async (req, res) => {
try {
const { name, email } = req.body;
const newUser = await User.create(name, email);
res.status(201).json(newUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
};
exports.updateUser = async (req, res) => {
try {
const { name, email } = req.body;
const updatedUser = await User.update(req.params.id, name, email);
res.json(updatedUser);
} catch (err) {
res.status(400).json({ message: err.message });
}
};
exports.deleteUser = async (req, res) => {
try {
await User.delete(req.params.id);
res.json({ message: 'User deleted successfully' });
} catch (err) {
res.status(500).json({ message: err.message });
}
};5. 創(chuàng)建路由 (routes/userRoutes.js)
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
// CRUD 路由
router.get('/', userController.getAllUsers);
router.get('/:id', userController.getUser);
router.post('/', userController.createUser);
router.put('/:id', userController.updateUser);
router.delete('/:id', userController.deleteUser);
module.exports = router;6. 應用入口 (app.js)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const userRoutes = require('./routes/userRoutes');
const app = express();
// 中間件
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 路由
app.use('/api/users', userRoutes);
// 錯誤處理
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ message: 'Something broke!' });
});
// 啟動服務器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});7. 創(chuàng)建數(shù)據(jù)庫表
在 MySQL 中執(zhí)行以下 SQL 創(chuàng)建 users 表:
CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
8. 測試 API
你可以使用 Postman 或 curl 測試這些端點:
- 獲取所有用戶:
GET /api/users - 訪問http://localhost:3000/api/users
- 結果為:

獲取單個用戶: GET /api/users/1
訪問http://localhost:3000/api/users/1

創(chuàng)建用戶:
在cmd窗口中執(zhí)行

curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john@example.com"}' http://localhost:3000/api/users
更新用戶:
在cmd窗口中執(zhí)行

curl -X PUT -H "Content-Type: application/json" -d '{"name":"John Updated","email":"john.new@example.com"}' http://localhost:3000/api/users/1
刪除用戶: DELETE /api/users/1
在cmd窗口中執(zhí)行

curl -X DELETE -H "Content-Type: application/json" http://localhost:3000/api/users/1
到此這篇關于Node.js 數(shù)據(jù)庫 CRUD 項目示例的文章就介紹到這了,更多相關Node.js 數(shù)據(jù)庫 CRUD內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
windows使用nvm對node進行版本管理切換的完整步驟
這篇文章主要介紹了windows使用nvm對node進行版本管理切換的完整步驟,在使用之前各位務必卸載掉自己安裝過的nvm或者node版本包括環(huán)境變量之類的,要保證自己的電腦完全沒有node環(huán)境,需要的朋友可以參考下2024-03-03
Node.js中path.join()優(yōu)勢例舉分析
在本篇文章里小編給大家整理的是一篇關于Node.js中path.join()優(yōu)勢例舉分析,有興趣的朋友們可以學習下。2021-08-08
node.js使用Moment.js js 時間計算方法示例小結
這篇文章主要介紹了node.js使用Moment.js js 時間計算方法,結合實例形式分析了Moment.js js模塊時間計算的常用操作技巧與相關注意事項,需要的朋友可以參考下2023-05-05

