You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
text1/src/dao/impl/CourseDaoImpl.java

70 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package dao.impl;
// 引入相关类和接口
import dao.CourseDao; // 数据访问对象DAO接口
import domain.Course; // 表示 Course 表数据结构的实体类
import org.springframework.dao.DataAccessException; // 数据访问异常类
import org.springframework.jdbc.core.BeanPropertyRowMapper; // 用于将结果集映射为实体类
import org.springframework.jdbc.core.JdbcTemplate; // Spring 的 JDBC 模板类
import utils.JDBCUtils; // 自定义工具类,用于获取数据源
/**
* CourseDaoImpl 实现了 CourseDao 接口,负责与数据库交互以操作 Course 数据表。
*/
public class CourseDaoImpl implements CourseDao {
// 使用 JdbcTemplate 进行数据库操作,通过 JDBCUtils 获取数据源
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 添加一门可选课程
* @param c 包含课程信息的 Course 对象
*/
@Override
public void addOptionalCourse(Course c) {
try {
// SQL 语句:向 course 表插入课程记录
String sql = "insert into course values(?,?,?,?)";
// 使用 JdbcTemplate 执行插入操作
template.update(sql, c.getC_id(), c.getC_name(), c.getT_id(), c.getC_info());
} catch (DataAccessException e) {
e.printStackTrace(); // 打印异常堆栈信息
}
}
/**
* 根据课程 ID 查找已选课程
* @param cid 课程 ID
* @return 查找到的课程对象;未找到时返回 null
*/
@Override
public Course findSelectCourseByCourseId(String cid) {
try {
// SQL 语句:根据课程 ID 查找对应课程信息
String sql = "select * from course where c_id = ?";
// 使用 JdbcTemplate 执行查询,并将结果映射为 Course 对象
Course course = template.queryForObject(sql, new BeanPropertyRowMapper<Course>(Course.class), cid);
return course; // 返回查询结果
} catch (DataAccessException e) {
e.printStackTrace(); // 打印异常堆栈信息
return null; // 查询失败时返回 null
}
}
/**
* 根据课程 ID 删除课程
* @param cid 课程 ID
*/
@Override
public void deleteServiceById(String cid) {
try {
// SQL 语句:根据课程 ID 删除对应课程记录
String sql = "delete from course where c_id=?";
// 使用 JdbcTemplate 执行删除操作
template.update(sql, cid);
} catch (DataAccessException e) {
e.printStackTrace(); // 打印异常堆栈信息
}
}
}