Access attributes from the database

Viewed 39

In this database table (administration), there are 4 attributes (email, name, password and mobile phone). I need that inside the if I can use each one of them but I don't know how I can access them.

How can I do this?

private void button_login_Click(object sender, EventArgs e)
{
    String username, user_password;

    username = txt_username.Text;
    user_password = txt_password.Text;

    try
    {
        String query = "SELECT * FROM administracao WHERE email = '"+txt_username.Text+"' AND password = '"+txt_password.Text+"'";

        SqlDataAdapter sda = new SqlDataAdapter(query, conn);
                
        DataTable dtable = new DataTable();
        sda.Fill(dtable);

        if (dtable.Rows.Count > 0)
        {
            // username = txt_username.Text;
            // user_password = txt_password.Text;
                    
            /* Menuform form2 = new Menuform();
            form2.Show();
            this.Hide();*/
        }
        else
        {
            MessageBox.Show("Invalid Login details", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            txt_username.Clear();
            txt_password.Clear();

            txt_username.Focus();
        }
    }
    catch
    {
        MessageBox.Show("Error");
    }
    finally
    {
        conn.Close();
    }
}
1 Answers

For communication with database I would strongly recommend Entity Framework.

In your case you can use SqlDataReader to get output data from sql query

Code Example:

public void GetData()
{
    var query = "your query";
    var connectionString = "your connection string";

    using (var connection = new SqlConnection(connectionString))
    {
        var command = new SqlCommand(query, connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();
        try
        {
            // Iterate all selected rows
            while (reader.Read())
            {
                int value1 = (int)reader["Int column name"];
                string value2 = (string)reader["String column name"];
            }
        }
        finally
        {
            reader.Close();
        }
    }
}

NOTE:

  1. In real project NEVER store passwords as plaintext. How to do it properly
  2. As people already mentioned in the comments, when you decide to execute query directly from the code NEVER combine query like you did, because of SQL Injection. Use parametrized SqlCommands. How to do it
Related