Node.js 数据库 CRUD 项目示例

希望使用Nodejs操作数据库做CRUD,用deepseek实战搜索"使用Nodejs对数据库表做CRUD的项目例子",找到了解决方案,如下图所示:

项目结构

复制代码
nodejs-crud-example/
├── config/
│   └── db.js          # 数据库连接配置
├── controllers/
│   └── userController.js # 业务逻辑
├── models/
│   └── userModel.js   # 数据库操作
├── 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. 配置数据库连接 (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. 创建模型 (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. 创建控制器 (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. 创建路由 (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. 创建数据库表

在 MySQL 中执行以下 SQL 创建 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

  • 创建用户:

    复制代码
    在cmd窗口中执行
    
    curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john@example.com"}' http://localhost:3000/api/users
  • 更新用户:

    复制代码
    在cmd窗口中执行
    
    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窗口中执行

  • curl -X DELETE -H "Content-Type: application/json" http://localhost:3000/api/users/1

相关推荐
小码哥0686 小时前
搭建短剧系统|海外短剧:从需求到上线的指南
网络·数据库·音视频·短剧小程序·短剧系统·短剧开发·短剧后台
HSunR7 小时前
ruoyi 若依 自定义注解 参数校验
java·前端·数据库
禾小西7 小时前
06丨Redis 数据同步:主从库如何实现数据一致?
数据库·redis·php
前端 贾公子7 小时前
LangGraph == 图的状态(State)管理 (上)
java·开发语言·数据库
薛晓刚8 小时前
PGA 超限的一次应急处置:扩容、清游标、杀会话
数据库
CJi0NG8 小时前
【自用】MySQL-事务
数据库·mysql
我不会插花弄玉8 小时前
4.string类型【由浅入深-redis】
数据库·redis·缓存
PHP实战开发录8 小时前
MySQL数字排序为什么乱
数据库·mysql·php
不停喝水9 小时前
【前端转全栈java速通课】 项目实战④7-11节 操作数据库-登录-注册-修改密码-注销-mubatis-plus简化crud-
java·前端·数据库
逍遥59660701010 小时前
网络设备交换机路由器 AI 配置助手
node.js·硬件工程