Update classManager.js

main
luoyonghuang 2 months ago
parent 32e96d8b03
commit 028c57a3f8

@ -4,43 +4,60 @@ const xlsx = require('xlsx');
const pool = require('../db'); const pool = require('../db');
const classManager = { const classManager = {
addClass: (req, res) => { addClass: async (req, res) => {
const filePath = req.file.path; // 创建students表的SQL语句
const createTableQuery = `
// 读取并解析Excel文件 CREATE TABLE IF NOT EXISTS students (
const workbook = xlsx.readFile(filePath); student_id INT AUTO_INCREMENT PRIMARY KEY,
const sheetName = workbook.SheetNames[0]; student_name VARCHAR(255) NOT NULL,
const worksheet = workbook.Sheets[sheetName]; score DECIMAL(5, 2),
call_count INT DEFAULT 0
const students = xlsx.utils.sheet_to_json(worksheet); );
`;
// 定义所需的字段 try {
const requiredFields = [ 'student_id', 'student_name']; // 先创建表
let hasError = false; await pool.query(createTableQuery);
students.forEach(student => { const filePath = req.file.path;
// 数据验证
const missingFields = requiredFields.filter(field =>!(field in student)); // 读取并解析Excel文件
if (missingFields.length > 0) { const workbook = xlsx.readFile(filePath);
console.error(`Student data is missing fields: ${missingFields.join(', ')}`); const sheetName = workbook.SheetNames[0];
hasError = true; const worksheet = workbook.Sheets[sheetName];
return;
} const students = xlsx.utils.sheet_to_json(worksheet);
// 将学生数据插入数据库 // 定义所需的字段
const query = 'INSERT INTO students (student_id, student_name, score, call_count) VALUES (?,?, 0, 0)'; const requiredFields = ['student_id','student_name'];
pool.query(query, [student.student_id, student.student_name], (error) => { let hasError = false;
if (error) {
console.error(`Error inserting student: ${student.name}`, error); students.forEach(student => {
// 数据验证
const missingFields = requiredFields.filter(field =>!(field in student));
if (missingFields.length > 0) {
console.error(`Student data is missing fields: ${missingFields.join(', ')}`);
hasError = true; hasError = true;
return;
} }
// 将学生数据插入数据库
const query = 'INSERT INTO students (student_id, student_name, score, call_count) VALUES (?,?, 0, 0)';
pool.query(query, [student.student_id, student.student_name], (error) => {
if (error) {
console.error(`Error inserting student: ${student.name}`, error);
hasError = true;
}
});
}); });
});
if (hasError) { if (hasError) {
res.status(500).json({ message: 'Error adding class. Some students were not added successfully.' }); res.status(500).json({ message: 'Error adding class. Some students were not added successfully.' });
} else { } else {
res.status(200).json({ message: 'Class added successfully!' }); res.status(200).json({ message: 'Class added successfully!' });
}
} catch (err) {
console.error('Error creating students table:', err);
res.status(500).json({ message: 'Error creating table during class addition.' });
} }
} }
}; };

Loading…
Cancel
Save