1

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

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

2 回答 2

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);
        }
    }
}
于 2013-07-26T01:50:27.390 回答
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;
        }
于 2013-07-26T02:04:31.170 回答