【问题标题】:Need to check a value from database to open a form accordingly需要检查数据库中的值以相应地打开表单
【发布时间】:2015-11-13 21:04:04
【问题描述】:

我有点业余,是数据库和查询的初学者。我想要做的是我有一个包含用户名和密码的表以及一个用户类型列。 检查用户名和密码后,我想检查 usertype 中的值,看看它是否为 1,如果 usertype 为 2,程序将以管理员权限打开表单,然后我想在没有管理员权限的情况下打开表单。 我不知道如何传递一个比较用户类型值的查询

private void button3_Click(object sender, EventArgs e)
{
    string cs = "provider = microsoft.ace.oledb.12.0; Data Source=C:\\Users\\Obm\\Desktop\\Emp.accdb; ";
    OleDbConnection conn = new OleDbConnection(cs);
    conn.Open();
    string q1 = "select username,password from MyUser where username = '" + textBox1.Text + "'and password = '" + textBox2.Text + "'";
    OleDbCommand cmd = new OleDbCommand(q1, conn);
    OleDbDataReader reader = cmd.ExecuteReader();

    if (reader.Read() )
    {
      MessageBox.Show("Success");
      //After this I want to check the value in usertype column.
    }
    else
    {
      MessageBox.Show("Try Again");
    }
}

【问题讨论】:

  • 使用 reader.Item("username")reader.Item("password") 如果可行,我将作为解决方案发布

标签: c# database ms-access


【解决方案1】:

您需要在查询中选择usertype 列,然后您才能从阅读器中读取该值。前提是usertype 是一个字符串:

private void button3_Click(object sender, EventArgs e)
{
    string cs = "provider = microsoft.ace.oledb.12.0; Data Source=C:\\Users\\Obm\\Desktop\\Emp.accdb; ";
    OleDbConnection conn = new OleDbConnection(cs);
    conn.Open();
    string q1 = "select username,password,usertype from MyUser where username = '" + textBox1.Text + "'and password = '" + textBox2.Text + "'";
    OleDbCommand cmd = new OleDbCommand(q1, conn);
    OleDbDataReader reader = cmd.ExecuteReader();

    while(reader.Read() )
    {
         MessageBox.Show("Success");
         string usertype = reader.GetString(2);
         //do something with usertype, eg if(usertype == "admin")...

     }
     reader.Close();
     conn.Close();
}

【讨论】:

  • 所以我无法获得 int 或任何其他类型的值?以及 reader.GetString(2) 中“2”的用途是什么; '
  • 是的,阅读器类有很多方法可以读取不同的类型,我只是以字符串为例。 2 是数组索引
【解决方案2】:

您没有从数据库中获取 usertype。即

string q1 = "select username,password from MyUser where username = '" + textBox1.Text + "'and password = '" + textBox2.Text + "'";

如果 usertype 是在 MyUser Table 中作为数据库中 Usertypes 表的外键可用的列,则您的查询需要看起来像这样,

string q1 = "Select username, password, usertype from MyUser where username = '" + textBox1.Text + "'and password = '" + textBox2.Text + "'";

一旦您从查询中检索到用户类型并在阅读器中执行,您就可以根据可用数据做出决定。即打开管理员表单或最终用户表单等。

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 2014-04-07
    • 2012-04-26
    • 2022-12-18
    • 1970-01-01
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多