import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; public class DataService { DatabaseConnection database; public DataService(DatabaseConnection database) { this.database = database; } public List getEmployees() { List employee = new ArrayList<>(); try { employee = tryGetEmployees(); }catch(SQLException e) { System.err.println("Hiba! A lekérdezés sikertelen!"); System.err.println(e.getMessage()); } return employee; } public List tryGetEmployees() throws SQLException { List employees = new ArrayList<>(); String sql = "select id, name, city, salary from employees"; Connection conn = database.connectDb(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { Employee employee = new Employee(); employee.id = rs.getInt("id"); employee.name = rs.getString("name"); employee.city = rs.getString("city"); employee.salary = rs.getDouble("salary"); employees.add(employee); } database.closeDb(conn); return employees; } public void tryInsertEmployee(String name, String city) throws SQLException { Connection conn = database.connectDb(); String sql = "insert into employees " + "(name, city) values " + "(?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, city); pstmt.execute(); database.closeDb(conn); } public void insertEmployee(String name, String city) { try { tryInsertEmployee(name, city); } catch (SQLException ex) { System.err.println("Hiba! A beszúrás sikertelen!"); } } }