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 Database {
public List<Employee> tryGetEmployees() throws SQLException {
List<Employee> employees = new ArrayList<>();
Connection conn = Mariadb.connectDb();
String sql = "select id, name, city, salary from employee";
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);
}
conn.close();
return employees;
}
public List<Employee> getEmployees() {
List<Employee> employees = null;
try {
employees = tryGetEmployees();
} catch (SQLException e) {
System.err.println("Hiba! A lekérdezés sikertelen!");
System.err.println(e.getMessage());
}
return employees;
}
public void tryInsertEmployee(
String name, String city, double salary)
throws SQLException {
Connection conn = Mariadb.connectDb();
String sql = "insert into employee " +
"(name, city, salary) values " +
"(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, city);
pstmt.setDouble(3, salary);
pstmt.execute();
conn.close();
}
public void insertEmployee(
String name, String city, double salary) {
try {
tryInsertEmployee(name, city, salary);
} catch (SQLException ex) {
System.err.println("Hiba! A beszúrás sikertelen!");
System.err.println(ex.getMessage());
}
}
}