-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathEmployeeDAO.java
More file actions
70 lines (63 loc) · 2.59 KB
/
EmployeeDAO.java
File metadata and controls
70 lines (63 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.example.employeemanager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class EmployeeDAO {
private final String url = "jdbc:mysql://localhost:3306/employeedb";
private final String user = "root";
private final String password = "password";
public Connection connect() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public void addEmployee(Employee employee) {
String sql = "INSERT INTO employees (id, name, department, salary) VALUES (?, ?, ?, ?)";
try (Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, employee.getId());
pstmt.setString(2, employee.getName());
pstmt.setString(3, employee.getDepartment());
pstmt.setDouble(4, employee.getSalary());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<Employee> getAllEmployees() {
List<Employee> employees = new ArrayList<>();
String sql = "SELECT * FROM employees";
try (Connection conn = connect(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
Employee employee = new Employee(
rs.getInt("id"),
rs.getString("name"),
rs.getString("department"),
rs.getDouble("salary")
);
employees.add(employee);
}
} catch (SQLException e) {
e.printStackTrace();
}
return employees;
}
public void updateEmployee(Employee employee) {
String sql = "UPDATE employees SET name = ?, department = ?, salary = ? WHERE id = ?";
try (Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, employee.getName());
pstmt.setString(2, employee.getDepartment());
pstmt.setDouble(3, employee.getSalary());
pstmt.setInt(4, employee.getId());
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteEmployee(int id) {
String sql = "DELETE FROM employees WHERE id = ?";
try (Connection conn = connect(); PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}