Do not worry, the connection will be closed by using
. Good thing, because if it had not been used, it would have more serious problems in the code. I do not know if you have other problems because I have not seen everything, I can only speak of this method in isolation.
The way I was doing it was wrong because nothing can be executed after an unconditional return
, which is the case of try-catch
. So how can an execution be done after it has already left the method? Usually when you want to ensure that the execution is done always before leaving the method you can use a try-finally
, which is exactly what using
does for features that need to be closed.
But something that I find strange is the exception being responsible for determining whether the user can log in or not, it seems very wrong, or at least somewhat robust, even more capturing Exception
which in this case is not only risky, it looks like it's pretty wrong , almost certainly something wrong will happen and cause failures undesirable. I'd take it out.
And would not use Boolean
this is not C # "for real", prefer bool
:)
Ideally, the OleDbDataReader
should be "protected" by using
as well. He suffers from the same connection problem. It is an external resource that needs to be closed.
Also, I'm concerned that the variable cmd
is not declared within this method. There may be a reason for this, but I doubt it is right.
I will understand that the exception is being used to detect whether the user is logged in or not. If this is not the case, you do not have to take this exception and return the result.
I'll put a shape that looks better:
public bool LogarUsuario(string Pnome, string Psenha) {
using (var conexao = new OleDbConnection(Conexao.stringConn)) {
conexao.Open();
var cmd = new OleDbCommand("SELECT * FROM Usuario WHERE Nome = ? AND Senha = ?", conexao);
cmd.Parameters.Add("@Nome", OleDbType.WChar).Value = Pnome;
cmd.Parameters.Add("@Senha", OleDbType.WChar).Value = Psenha;
using (OleDbDataReader reader = cmd.ExecuteReader()) {
reader.Read();
if (reader.HasRows) {
Nome = reader[1];
}
return reader.HasRows;
}
}
}