feat: 实现成绩管理系统核心功能
添加响应工具、错误处理中间件和数据库模型 创建用户、学生、课程和成绩相关服务 实现管理员、教师和学生控制器的基本功能 重构路由处理并优化数据库查询
This commit is contained in:
@@ -11,54 +11,32 @@ const pool = mysql.createPool({
|
||||
queueLimit: 0
|
||||
});
|
||||
|
||||
// 测试数据库连接
|
||||
async function testConnection() {
|
||||
try {
|
||||
const connection = await pool.getConnection();
|
||||
console.log('数据库连接成功');
|
||||
connection.release();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('数据库连接失败:', error.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行查询
|
||||
async function query(sql, params) {
|
||||
try {
|
||||
const [rows] = await pool.execute(sql, params);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
console.error('数据库查询错误:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// 执行事务
|
||||
async function executeTransaction(operations) {
|
||||
const connection = await pool.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
|
||||
for (const operation of operations) {
|
||||
await connection.execute(operation.sql, operation.params);
|
||||
// 封装基本查询方法
|
||||
const query = async (sql, params) => {
|
||||
try {
|
||||
const [rows] = await pool.execute(sql, params);
|
||||
return rows;
|
||||
} catch (error) {
|
||||
console.error('Database query error:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
await connection.commit();
|
||||
console.log('事务执行成功');
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
console.error('事务执行失败:', error.message);
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 测试连接
|
||||
const testConnection = async () => {
|
||||
try {
|
||||
const connection = await pool.getConnection();
|
||||
console.log('数据库连接成功');
|
||||
connection.release();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('数据库连接失败:', error.message);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
pool,
|
||||
query,
|
||||
executeTransaction,
|
||||
testConnection
|
||||
pool,
|
||||
query,
|
||||
testConnection
|
||||
};
|
||||
Reference in New Issue
Block a user