3.3 测试数据库查询
- 新建一个文件夹model,在这个文件夹下新建weaponSkinModel.js文件
// model/weaponSkinModel.js
const { pool } = require('../config/db');
// 👉 第1个功能:查询所有武器
async function getAllWeaponSkins() {
try {
const [rows] = await pool.execute('SELECT * FROM weapon_skins ORDER BY id DESC');
return rows;
} catch (error) {
console.error('❌ 查询所有数据失败:', error.message);
throw error;
}
}
// 只暴露当前开发的功能
module.exports = {
getAllWeaponSkins
};
- 创建外层index.js文件,开始对上面代码做测试,此时目录结构如下。注意层级
weapon
├─ config/ # 配置文件夹
│ └─ db.js # 数据库连接池配置
├─ model/ # 数据模型/CRUD 文件夹
│ └─ weaponSkinModel.js # 武器皮肤表 CRUD 逻辑
├─ .env # 环境变量
├─ index.js # 入口文件(逐个功能测试)
└─ package.json - 在index.js文件中,创建测试代码
// index.js
const { testPoolConnection } = require('./config/db');
const weaponSkinModel = require('./model/weaponSkinModel');
// 👉 测试 1:查询所有数据(对应 getAllWeaponSkins 功能)
async function testGetAllWeaponSkins() {
console.log('===== 开始测试:查询所有数据 =====');
try {
// 先测试连接池
await testPoolConnection();
// 调用查询函数
const result = await weaponSkinModel.getAllWeaponSkins();
console.log('查询成功!结果:');
console.log(result.length > 0 ? result : '暂无数据');
} catch (error) {
console.log('查询失败!原因:', error.message);
}
console.log('===== 测试结束:查询所有数据 =====\n');
}
// 👉 执行当前测试(只运行这一个)
testGetAllWeaponSkins();
- 运行index.js文件,可以看到控制台输出正常