diff --git a/classManager.js b/classManager.js index c331a51..fa6648e 100644 --- a/classManager.js +++ b/classManager.js @@ -4,43 +4,60 @@ const xlsx = require('xlsx'); const pool = require('../db'); const classManager = { - addClass: (req, res) => { - const filePath = req.file.path; - - // 读取并解析Excel文件 - const workbook = xlsx.readFile(filePath); - const sheetName = workbook.SheetNames[0]; - const worksheet = workbook.Sheets[sheetName]; - - const students = xlsx.utils.sheet_to_json(worksheet); - - // 定义所需的字段 - const requiredFields = [ 'student_id', 'student_name']; - let hasError = false; - - 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; - return; - } + addClass: async (req, res) => { + // 创建students表的SQL语句 + const createTableQuery = ` + CREATE TABLE IF NOT EXISTS students ( + student_id INT AUTO_INCREMENT PRIMARY KEY, + student_name VARCHAR(255) NOT NULL, + score DECIMAL(5, 2), + call_count INT DEFAULT 0 + ); + `; + try { + // 先创建表 + await pool.query(createTableQuery); + + const filePath = req.file.path; + + // 读取并解析Excel文件 + const workbook = xlsx.readFile(filePath); + const sheetName = workbook.SheetNames[0]; + const worksheet = workbook.Sheets[sheetName]; + + const students = xlsx.utils.sheet_to_json(worksheet); - // 将学生数据插入数据库 - 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); + // 定义所需的字段 + const requiredFields = ['student_id','student_name']; + let hasError = false; + + 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; + 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) { - res.status(500).json({ message: 'Error adding class. Some students were not added successfully.' }); - } else { - res.status(200).json({ message: 'Class added successfully!' }); + if (hasError) { + res.status(500).json({ message: 'Error adding class. Some students were not added successfully.' }); + } else { + 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.' }); } } };