当前位置: 首页 > article >正文

expressjs,MySQL,实现分页查询接口

在 Express.js 中实现一个分页查询接口,并使用 MySQL 作为数据库,你可以按照以下步骤进行。我们将使用 mysql2 库来连接 MySQL 数据库,并使用 sequelize 或直接编写 SQL 查询来实现分页功能。

1. 安装必要的依赖

首先,你需要安装 expressmysql2 库。如果你打算使用 Sequelize ORM,也可以安装 sequelize

npm install express mysql2
# 如果你打算使用 Sequelize
# npm install sequelize mysql2

2. 设置 Express 应用和 MySQL 连接

创建一个 app.js 文件,并设置 Express 应用和 MySQL 连接。

const express = require('express');
const mysql = require('mysql2/promise');

const app = express();
const port = 3000;

// MySQL 连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'yourpassword',
  database: 'yourdatabase'
};

let connection;

// 连接到 MySQL 数据库
mysql.createConnection(dbConfig)
  .then(conn => {
    connection = conn;
    console.log('Connected to MySQL');
    app.listen(port, () => {
      console.log(`Server is running on http://localhost:${port}`);
    });
  })
  .catch(err => {
    console.error('Error connecting to MySQL:', err);
  });

// 定义一个关闭服务器的函数,以便在进程退出时关闭数据库连接
const shutdown = () => {
  connection.end();
  process.exit(0);
};

process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

3. 实现分页查询接口

接下来,我们实现一个分页查询接口。假设我们有一个名为 users 的表,并且我们想要分页查询用户数据。

app.get('/users', async (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  const offset = (page - 1) * limit;

  try {
    const [rows, fields] = await connection.execute(
      'SELECT * FROM users LIMIT ? OFFSET ?',
      [limit, offset]
    );

    const totalRows = await connection.execute('SELECT COUNT(*) AS total FROM users')[0][0].total;
    const totalPages = Math.ceil(totalRows / limit);

    res.json({
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: parseInt(totalPages),
      totalRows: parseInt(totalRows),
      data: rows
    });
  } catch (err) {
    console.error('Error executing query:', err);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

4. 完整代码

将上述代码片段组合在一起,得到完整的 app.js 文件:

const express = require('express');
const mysql = require('mysql2/promise');

const app = express();
const port = 3000;

// MySQL 连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'yourpassword',
  database: 'yourdatabase'
};

let connection;

// 连接到 MySQL 数据库
mysql.createConnection(dbConfig)
  .then(conn => {
    connection = conn;
    console.log('Connected to MySQL');
    app.listen(port, () => {
      console.log(`Server is running on http://localhost:${port}`);
    });
  })
  .catch(err => {
    console.error('Error connecting to MySQL:', err);
  });

// 分页查询接口
app.get('/users', async (req, res) => {
  const { page = 1, limit = 10 } = req.query;
  const offset = (page - 1) * limit;

  try {
    const [rows, fields] = await connection.execute(
      'SELECT * FROM users LIMIT ? OFFSET ?',
      [limit, offset]
    );

    const totalRows = await connection.execute('SELECT COUNT(*) AS total FROM users')[0][0].total;
    const totalPages = Math.ceil(totalRows / limit);

    res.json({
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: parseInt(totalPages),
      totalRows: parseInt(totalRows),
      data: rows
    });
  } catch (err) {
    console.error('Error executing query:', err);
    res.status(500).json({ error: 'Internal Server Error' });
  }
});

// 定义一个关闭服务器的函数,以便在进程退出时关闭数据库连接
const shutdown = () => {
  connection.end();
  process.exit(0);
};

process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

5. 运行应用

确保你的 MySQL 数据库正在运行,并且有一个名为 users 的表。然后运行你的 Express 应用:

node app.js

现在,你可以通过访问 http://localhost:3000/users?page=1&limit=10 来获取分页的用户数据。

注意事项

  1. 安全性:在生产环境中,请确保对输入进行验证和清理,以防止 SQL 注入攻击。
  2. 错误处理:添加更详细的错误处理,以便在出现问题时能够更容易地调试。
  3. 性能:对于大型数据集,考虑使用索引来优化查询性能。

希望这能帮助你实现分页查询接口!


http://www.kler.cn/news/335574.html

相关文章:

  • 中间件介绍
  • 在Ubuntu 16.04上使用Logrotate管理日志文件
  • 【ECMAScript 从入门到进阶教程】第三部分:高级主题(高级函数与范式,元编程,正则表达式,性能优化)
  • ChatGPT进行翻译
  • 目录工具类 - C#小函数类推荐
  • 大数据新视界 --大数据大厂之 Ibis:独特架构赋能大数据分析高级抽象层
  • Ubuntu 通过 Docker 搭建 GitLab
  • 数据结构与算法篇((原/反/补)码 进制)
  • 使用axios封装AJAX
  • 计算机毕业设计 基于Python的社交音乐分享平台的设计与实现 Python+Django+Vue 前后端分离 附源码 讲解 文档
  • DOS 命令学习笔记
  • Apollo配置中心实战
  • PHP 基础语法详解
  • Java项目实战II基于Java+Spring Boot+MySQL的大创管理系统(源码+数据库+文档)
  • Spring MVC__@RequestMapping注解、获取请求参数、域对象共享数据、视图、Restful
  • 【力扣 | SQL题 | 每日四题】力扣2082, 2084, 2072, 2112, 180
  • 24-10-2-读书笔记(二十二)-《契诃夫文集》(一)上([俄] 契诃夫 [译] 汝龙)啊!真想生活。
  • mac M2安装单机版 MongoDB 7.x
  • Spring Cloud面试题收集
  • Python知识点:在Python编程中,如何使用Gensim进行主题建模