检查数据库的用户名或密码Oledb Connection

时间:2013-07-26 01:11:21

标签: c# .net ado.net

我正在尝试检查一个数据库,我已连接到我的程序以获取用户名和密码我已经进行了查询但是如何针对表格进行检查。

    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);
            }
        }
    }

2 个答案:

答案 0 :(得分:3)

你已经非常接近了,让我们稍微修改一下:

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);
        }
    }
}

答案 1 :(得分:0)

如果您只是想检查用户名和密码是否存在,您可以这样做

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;
        }