Attendance(考勤表) 字段名 类型 注释 其他 id int 序号 主键,非空 attendancename varchar(50) 考勤 空 basepay decimal(10) 基本工资 空 根据以上内容用java写出增删改查方法类
时间: 2023-06-16 14:06:27 浏览: 187
jsf+hibernate+javabean完成对表的增删查改
3星 · 编辑精心推荐
以下是一个参考实现:
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class AttendanceDAO {
private Connection conn;
public AttendanceDAO(Connection conn) {
this.conn = conn;
}
public void addAttendance(Attendance attendance) throws SQLException {
String sql = "INSERT INTO Attendance (id, attendancename, basepay) VALUES (?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, attendance.getId());
stmt.setString(2, attendance.getAttendanceName());
stmt.setBigDecimal(3, attendance.getBasePay());
stmt.executeUpdate();
}
public void updateAttendance(Attendance attendance) throws SQLException {
String sql = "UPDATE Attendance SET attendancename = ?, basepay = ? WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, attendance.getAttendanceName());
stmt.setBigDecimal(2, attendance.getBasePay());
stmt.setInt(3, attendance.getId());
stmt.executeUpdate();
}
public void deleteAttendance(int id) throws SQLException {
String sql = "DELETE FROM Attendance WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
stmt.executeUpdate();
}
public List<Attendance> getAllAttendance() throws SQLException {
String sql = "SELECT * FROM Attendance";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
List<Attendance> attendances = new ArrayList<>();
while (rs.next()) {
int id = rs.getInt("id");
String attendanceName = rs.getString("attendancename");
BigDecimal basePay = rs.getBigDecimal("basepay");
Attendance attendance = new Attendance(id, attendanceName, basePay);
attendances.add(attendance);
}
return attendances;
}
public Attendance getAttendanceById(int id) throws SQLException {
String sql = "SELECT * FROM Attendance WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
String attendanceName = rs.getString("attendancename");
BigDecimal basePay = rs.getBigDecimal("basepay");
Attendance attendance = new Attendance(id, attendanceName, basePay);
return attendance;
} else {
return null;
}
}
}
```
其中 `Attendance` 类代表一个考勤记录,有三个字段:`id`、`attendanceName`、`basePay`。`AttendanceDAO` 类是对考勤记录进行增删改查的方法类,其中 `conn` 是一个数据库连接对象。这里使用了 `PreparedStatement` 来防止 SQL 注入攻击。
阅读全文