Node.js 数据库 CRUD 项目示例详解(完美解决方案)

2025-04-17 04:50

本文主要是介绍Node.js 数据库 CRUD 项目示例详解(完美解决方案),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Node.js数据库CRUD项目示例详解(完美解决方案)》:本文主要介绍Node.js数据库CRUD项目示例详解(完美解决方案),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考...

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

Node.js 数据库 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-ewww.chinasem.cnxample
cd nodejs-crud-example
npm init -y
npm install express mysql2 body-parser cors

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

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(
android      '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 = awChina编程ait User.getAll();
    res.json(users);
  }php 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);
  编程China编程  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
  • 结果为:

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

获取单个用户GET /api/users/1

访问http://localhost:3000/api/users/1

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

创建用户:

在cmd窗口中执行

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john@example.com"}' http://localhost:3000/api/users

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

更新用户:

在cmd窗口中执行

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

curl -X PUT -H "Content-Type: application/json" -d '{"name":"John Updated","email":"john.new@example.com"}' http://localhost:3000/api/users/1

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

删除用户DELETE /api/users/1

在cmd窗口中执行

Node.js 数据库 CRUD 项目示例详解(完美解决方案)

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

到此这篇关于Node.js 数据库 CRUD 项目示例的文章就介绍到这了,更多相关Node.js 数据库 CRUD内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于Node.js 数据库 CRUD 项目示例详解(完美解决方案)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154253

相关文章

MySQL数据库双机热备的配置方法详解

《MySQL数据库双机热备的配置方法详解》在企业级应用中,数据库的高可用性和数据的安全性是至关重要的,MySQL作为最流行的开源关系型数据库管理系统之一,提供了多种方式来实现高可用性,其中双机热备(M... 目录1. 环境准备1.1 安装mysql1.2 配置MySQL1.2.1 主服务器配置1.2.2 从

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

MyBatis常用XML语法详解

《MyBatis常用XML语法详解》文章介绍了MyBatis常用XML语法,包括结果映射、查询语句、插入语句、更新语句、删除语句、动态SQL标签以及ehcache.xml文件的使用,感兴趣的朋友跟随小... 目录1、定义结果映射2、查询语句3、插入语句4、更新语句5、删除语句6、动态 SQL 标签7、ehc

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

从基础到高级详解Go语言中错误处理的实践指南

《从基础到高级详解Go语言中错误处理的实践指南》Go语言采用了一种独特而明确的错误处理哲学,与其他主流编程语言形成鲜明对比,本文将为大家详细介绍Go语言中错误处理详细方法,希望对大家有所帮助... 目录1 Go 错误处理哲学与核心机制1.1 错误接口设计1.2 错误与异常的区别2 错误创建与检查2.1 基础

k8s按需创建PV和使用PVC详解

《k8s按需创建PV和使用PVC详解》Kubernetes中,PV和PVC用于管理持久存储,StorageClass实现动态PV分配,PVC声明存储需求并绑定PV,通过kubectl验证状态,注意回收... 目录1.按需创建 PV(使用 StorageClass)创建 StorageClass2.创建 PV

vite搭建vue3项目的搭建步骤

《vite搭建vue3项目的搭建步骤》本文主要介绍了vite搭建vue3项目的搭建步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 目录1.确保Nodejs环境2.使用vite-cli工具3.进入项目安装依赖1.确保Nodejs环境

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

一文详解Python如何开发游戏

《一文详解Python如何开发游戏》Python是一种非常流行的编程语言,也可以用来开发游戏模组,:本文主要介绍Python如何开发游戏的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、python简介二、Python 开发 2D 游戏的优劣势优势缺点三、Python 开发 3D