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. 性能:对于大型数据集,考虑使用索引来优化查询性能。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

读心悦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值