Verification in login form

-2

I'm not able to do a check in the database, to make sure the user exists. Here is the code:

private void button1_Click_1(object sender, EventArgs e)
{
    string conexao = "SERVER = localhost; DATABASE = dizimistas; UID = root; PASSWORD = senha00789;";
    string query = "SELECT idusuario FROM USUARIOS WHERE nomeusuario = @usuario and senhausuario = @senha;";

    using (MySqlConnection objConexao = new MySqlConnection(conexao))
    {
        objConexao.Open();
        try
        {
            MySqlCommand command = new MySqlCommand(query, objConexao);
            command.Parameters.AddWithValue("@usuario", txtUsuario);
            command.Parameters.AddWithValue("@senha", txtSenha);

            int? id = (int?)command.ExecuteScalar();
            if (id.HasValue)
            {
                FormPrincipal form = new FormPrincipal();
                form.Show();
            } else
            {
                MessageBox.Show("Usuário ou senha inválidos!");
            }
        }
        finally
        {
            objConexao.Close();
        }
    }
}

If the query returns true (User exists), then it will be taken to another form. But everything I put in this IF, visual studio does not accept.

    
asked by anonymous 29.11.2017 / 12:47

1 answer

3

Dear Peter, first of all, never use string concatenation to build your SQL clauses. This way you avoid the SQL Injection SQL Injection .

I have an example of how you would use parameters.

string conexao = "SERVER = localhost; DATABASE = dizimistas; UID = root; PASSWORD = senha00789;";
string query = "SELECT idusuario FROM USUARIOS WHERE usuario = @usuario and senha = @senha;";

using (MySqlConnection objConexao = new MySqlConnection(conexao))
{
    objConexao.Open();
    try
    {
        MySqlCommand command = new MySqlCommand(query, objConexao);
        command.Parameters.AddWithValue("@usuario", txtUsuario);
        command.Parameters.AddWithValue("@senha", txtSenha);

        var dataReader = command.ExecuteReader();
        if (dataReader.Read())
        {

        }
    }
    finally
    {
        objConexao.Close();
    }                
}

The using clause provides convenient syntax that ensures the correct use of IDisposable objects. I use try finally after opening the connection, to ensure that when I finish the whole operation within try the connection is always closed.

    
29.11.2017 / 12:56