3.5 测试数据库删除
新增删除功能代码
在index.js中增加测试代码
重复上述测试步骤
3.6 测试数据库修改
新增修改功能代码
JavaScript
运行代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// model/weaponSkinModel.js(新增)
// 👉 第4个功能:按 ID 修改价格
async function updateWeaponSkinPrice(id, newPrice) {
if (!id) throw new Error('ID 不能为空');
if (typeof newPrice !== 'number' || newPrice < 0) {
throw new Error('价格必须为非负数值');
}
try {
const [result] = await pool.execute(
'UPDATE weapon_skins SET price = ? WHERE id = ?',
[newPrice, id]
);
if (result.affectedRows === 0) throw new Error(未找到 ID=${id} 的数据);
return { success: true, message: 价格更新为 ${newPrice} 元 };
} catch (error) {
console.error(❌ 修改 ID=${id} 价格失败:, error.message);
throw error;
}
}
// 更新暴露
module.exports = {
getAllWeaponSkins,
addWeaponSkin,
deleteWeaponSkin,
updateWeaponSkinPrice // 新增
};
在index.js中增加测试代码
JavaScript
运行代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 👉 测试 4:修改价格(对应 updateWeaponSkinPrice 功能)
async function testUpdateWeaponSkinPrice() {
console.log('===== 开始测试:修改价格 =====');
const testId = 3; // 实际存在的 ID
const newPrice = 1799.99;
try {
await testPoolConnection();
const result = await weaponSkinModel.updateWeaponSkinPrice(testId, newPrice);
console.log('修改结果:', result);
} catch (error) {
console.log('修改失败!原因:', error.message);
}
console.log('===== 测试结束:修改价格 =====\n');
}
// 👉 执行当前测试(只运行这一个)
// testGetAllWeaponSkins();
// testAddWeaponSkin();
// testDeleteWeaponSkin(1);
testUpdateWeaponSkinPrice();
控制台和数据库双向验证,发现符合逻辑
案例练习
增加一个根据id,扣减库存的功能。函数入参为:id,stock两个参数
自己做完后再来参考:weaponSkinModel.js
JavaScript
运行代码
复制代码
自己做完后再来参考:index.js
JavaScript
运行代码
复制代码