user2552211
user2552211

Reputation: 143

Check Database for username or password OledDb Connection

I'm trying to check a database that i have connect to my program for user name and password i have my query made but how would i go about checking it against a table.

    private void button1_Click(object sender, EventArgs e)
    {
        Menu m1 = new Menu();
        string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserAccounts.accdb; Persist Security Info=False;";
        OleDbCommand cmd = new OleDbCommand("Select * from UserAccounts where Username = " +userBox.Text + " and Password] = " + Password.Text + "");
        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            try
            {
                conn.Open();
                this.Hide();
                m1.Show();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }
    }

Upvotes: 1

Views: 6130

Answers (2)

Karsten
Karsten

Reputation: 83

If you simply want to check if a username and password exists you could do like this

public bool IsValid(string username, string password)
        {
            string connectionString = @"...connectionstring";


            string SQL = "SELECT * FROM UserAccounts where [Username]='" + username + "' and [Password]='" + password + "'";

            OdbcConnection conn = new OdbcConnection(connectionString);

            OdbcCommand cmd = new OdbcCommand(SQL);
            cmd.Connection = conn;

            conn.Open();

            OdbcDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                return true;
            }

            return false;
        }

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67918

You're pretty close already, let's just modify it a little bit:

private void button1_Click(object sender, EventArgs e)
{
    Menu m1 = new Menu();
    string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserAccounts.accdb; Persist Security Info=False;";
    using (OleDbConnection conn = new OleDbConnection(connectionString))
    {
        try
        {
            conn.Open();
            using (OleDbCommand cmd = new OleDbCommand("Select * from UserAccounts where Username = @Username and Password = @Password"))
            {
                cmd.Parameters.AddWithValue("@Username", userBox.Text);
                cmd.Parameters.AddWithValue("@Password", Password.Text);

                using (OleDbDataReader r = cmd.ExecuteReader())
                {
                    if (r.HasRows)
                    {
                        // do something here
                    }
                }
            }
            this.Hide();
            m1.Show();
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }
    }
}

Upvotes: 3

Related Questions