I want to populate a TableView with players from MySQL database. To load all players I am using
public void loadPlayerData() throws SQLException, ClassNotFoundException {
Connection conn = ConnectionDB.connector();
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM player") ;
while (rs.next()) { playersList.add(new Players
(rs.getString("name"), rs.getString("familyName"),
rs.getString("email"), rs.getString("activeTeam")));
}
rs.close();
and it works fine.. but I need to load only specific players that belong to a team (the name of the team is displayed in a TextField) and I did the following :
public void loadPlayerData() throws SQLException, ClassNotFoundException {
Connection conn = ConnectionDB.connector();
String s = teamName.getText();
ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM player WHERE activeTeam='" + s + "'") ;
while (rs.next()) { playersList.add(new Players
(rs.getString("name"), rs.getString("familyName"),
rs.getString("email"), rs.getString("activeTeam")));
}
rs.close();
but it doesn't load anything... I guess I am doing wrong in the syntax,writing wrong the WHERE clause, but all I researched pointed me to the same thing so I guess I have to ask here
@Rzwitserloot gave an excellent explanation, I suggest the following approach
Edit
Added try with resources construct so it can prevent leaks.
public void loadPlayerData() throws SQLException, ClassNotFoundException {
try (Connection connection = ConnectionDb.connector) {
String s = teamName.getText();
PreparedStatement myStmt;
myStmt = conn.prepareStatement("select * from player where activeTeam = ?");
myStmt.setString(1, s);
try (ResultSet rs = myStmt.executeQuery()) {
while (rs.next()) {
playersList.add(new Players
(rs.getString("name"), rs.getString("familyName"),
rs.getString("email"), rs.getString("activeTeam")));
}
}
}
}