In the "user" table of the database there will always be a record with a username and password to be able to log in for the first time.
I must know if the username and password entered are the same as those stored in my database. Also, I want that instead of getting the profile_id type INT, I get the name of the profile type String.
All the data that I ask for, I will show them in labels text for visualization purposes only. To display: Connected user: name, user, pass, etc..
I don't understand SQL statements well, it's my second time working with them and I need help to know if it's correct.
Code:
public boolean login(String usuario, String contrasena) {
Dato_login d_lgn = new Dato_login();
boolean resultado = false;
sSQL = "SELECT u.nombre, u.apellido, u.usuario, u.contrasena, u.id_perfil FROM usuario U INNER JOIN perfil P ON p.id_perfil=u.id_perfil WHERE u.usuario='"
+ usuario + "' AND u.contrasena='" + contrasena + "'";
// Java 7 try-with-resources
try (Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sSQL)) {
while (rs.next()) {
if (d_lgn.getContrasena().equals(contrasena)) {
resultado = true;
} else {
resultado = false;
}
d_lgn.setPerfil(rs.getString("id_perfil"));
d_lgn.setUsuario(rs.getString("usuario"));
d_lgn.setNombre(rs.getString("nombre"));
d_lgn.setApellido(rs.getString("apellido"));
d_lgn.setContrasena(rs.getString("contrasena"));
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "SQLException:\n" + e, "Error: Logica_usuario.tableRegistros(String buscar)", JOptionPane.ERROR_MESSAGE);
}
return resultado;
}
Note: "Data_login d_lgn" is to be able to access that class that contains the getters and setters to save the information locally and display it faster.
Is my SQL statement correct? Am I asking for the profile name instead of the id_profile? Am I comparing the username and password correctly?
Help please, it would be greatly appreciated.
Your question is to avoid sql injections I guess. Well, you only need to compare the username and password obtained from the DB and what you brought from the view.
So you check the value of the view with the value of the database. Be careful, check username and password, in both you can get an injection.
It's simpler, you don't have to do a JOIN, and just check if there is any record that meets the WHERE or there are no records for that WHERE.