Verification in login form

Asked

Viewed 98 times

-2

I am not able to do a check in the database, to make sure that the user exists. Follow 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. However everything I put in this IF, visual studio does not accept.

  • Apart from the comparison that makes no sense, the query, right?

  • I’m new to C#. I’m sorry I’m a layman! For me, Doc.Selectcommand was running the query

1 answer

3


Dear Pedro, first of all, never use string concatenation to assemble your SQL clauses. So you avoid the SQL Injection.

I put together an example of how I would look using 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 clause using provides convenient syntax that ensures correct use of objects Idisposable. Use the try finally after opening the connection, to ensure that when completing the entire operation within the try the connection is always closed.

  • Pablo, you have two "@user", when I compile the program and click login, nothing happens. Check if I’ve made the call to the new form: if (dataReader.Read()) { Formprincipal form = new Formprincipal(); form.Show(); }

  • I corrected the question of having two @user, in copy and paste I did not edit. I made a change in command execution too, I switched to Executescalar. And the execution of the Form would be basically that right there.

  • I adapted an Else, var usuario = command.Executescalar(); if (user != null) { Formmain form = new Formprincipal(); form. Show(); } Else { Messagebox.Show("Invalid user or password!"); } .

  • Remember that for database functions it would be better to use another layer, and not directly at the click of the button!

  • I was missing some knowledge about Executescalar, but I already corrected the answer and added some more details.

  • Still keeps falling into the password Else or invalid user :(

  • 1

    Pedro, put a breackpoint and check the variables txtUsuario and txtNo, I believe these two are visual components, being visual components, put one . Text at the end to pick up the value typed by the user.

  • Now it is! However ta giving this error in IF(id.Hasvalue): System.Invalidcastexception: 'Specified conversion is not valid.'

  • on your table USUARIOS, which name and type of primary key?

  • int(11) unsigned zerofill, auto_increment. Name: idusuario

  • I made an edit on the reply, look at the comments in the chat.

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.