Update scoreManager.js

main
luoyonghuang 2 months ago
parent acb2e42f98
commit a4cf04db29

@ -2,7 +2,78 @@ const pool = require('../db');
async function updateScore(req, res) {
const { student_id, points } = req.body; //假设前端发送的数据是这两部分
const pool = require('../db');
async function updateScore(req, res) {
const { student_id, points } = req.body;
let connection; // 在try块外部声明connection
try {
connection = await pool.getConnection();
// 更新学生的积分并增加点名次数
const [result] = await connection.query(
'UPDATE students SET score = score + ?, call_count = call_count + 1 WHERE student_id = ?',
[points, student_id]
);
if (result.affectedRows > 0) {
// 查询更新后的分数
const [rows] = await connection.query(
'SELECT score FROM students WHERE student_id = ?',
[student_id]
);
if (rows.length > 0) {
const updatedScore = rows[0].score;
return res.send(String(updatedScore));
} else {
return res.status(404).send('学生不存在');
}
} else {
return res.status(404).send('学生不存在');
}
} catch (error) {
console.error('数据库操作失败:', error);
return res.status(500).send('更新积分失败');
} finally {
if (connection) {
connection.release(); // 只有在connection已被赋值时才调用release
}
}
}
async function getStudentScore(req, res) {
const { student_id } = req.body;
let connection;
try {
connection = await pool.getConnection();
// 查询指定学生的分数
const [rows] = await connection.query(
'SELECT score FROM students WHERE student_id =?',
[student_id]
);
if (rows.length > 0) {
const score = rows[0].score;
// 修改这里构建包含student_id和score的对象并返回
return res.json({ student_id, score });
} else {
return res.status(404).json({ message: '学生不存在' });
}
} catch (error) {
console.error('数据库操作失败:', error);
return res.status(500).json({ error: '获取分数失败' });
} finally {
if (connection) {
connection.release();
}
}
}
module.exports = { updateScore, getStudentScore };
try {
const connection = await pool.getConnection();
const [result] = await connection.query('UPDATE students SET score = score + ?, call_count = call_count + 1 WHERE student_id = ?', [points, student_id]);

Loading…
Cancel
Save