Error trying to login user with mysql

1

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)

    
asked by anonymous 30.08.2017 / 02:06

1 answer

2

You are calling the getConexão() out of the method that executes the command, and then calls again within the method. So you pass the command with one connection, and open another.

One of the correct forms would look something like this:

private static bool testarLogin(string usuario, string senha)
{
    using (MySqlConnection conexao = getConexão())
    {
        string query = "SELECT * FROM tbl_usuario WHERE (usuario=@Usuario OR email=@Usuario) AND senha=@Senha";
        conexao.Open();
        MySqlCommand command = new MySqlCommand(query, conexao );
        command.Parameters.AddWithValue("@Usuario", usuario);
        command.Parameters.AddWithValue("@Senha", senha);
        int resultado = command.ExecuteScalar();
        conexao.Close();

        return resultado > 0;
     }
}

ps. I know it works with ã, but I confess it gave me an agony to see the signature of the method written like this. Look for nomenclature patterns =]

    
30.08.2017 / 04:12