I am trying to log a user to my system using a MySql database, but it is returning me a NullReference error. I've tried to check if it was null before converting to string, but the error persists. Why does the mistake happen? How to fix?
Method where I execute the query:
private static string executarQueryScalar(MySqlCommand command)
{
MySqlConnection connect = getConexão();
try
{
connect.Open();
return command.ExecuteScalar().ToString(); //Linha do erro
}
catch
{
return null;
}
finally
{
connect.Close();
}
}
Method where I call it:
private static bool testarLogin(string usuario, string senha)
{
string query = "SELECT * FROM tbl_usuario WHERE (usuario=@Usuario OR email=@Usuario) AND senha=@Senha";
MySqlCommand command = new MySqlCommand(query, getConexão());
command.Parameters.AddWithValue("@Usuario", usuario);
command.Parameters.AddWithValue("@Senha", senha);
return Convert.ToInt32(executarQueryScalar(command)) > 0;
}
getConnection () method:
private static MySqlConnection getConexão()
{
string servidor = "server", banco = "database", banco_usuario = "user", banco_senha = "password";
return new MySqlConnection($"Server={servidor};Database={banco};Uid={banco_usuario};Pwd={banco_senha}");
}
Error presented:
System.NullReferenceException: Object reference not set to an instance of an object. in MySql.Data.MySqlClient.MySqlCommand.ExecuteScalar () em PureCheats.Validações.ChecarLogin.execuutarQueryScalar (MySqlCommand command)