【发布时间】:2021-04-14 03:18:13
【问题描述】:
我对数据库和SQL不太了解,所以我想在这里寻求帮助,虽然我知道这应该是基本知识,但作为一个新手我不知道从哪里开始。
我在弄清楚如何从数据表中获取特定值时遇到问题,我已经使用以下代码在 form2 中拥有 ID:
cmd = new SqlCommand("select UserID from Users where UserName='" + textBox1.Text + "' and UserPassword='" + textBox2.Text + "'", cn);
object result = cmd.ExecuteScalar();
if (result != null)
{
loginresult = 1;
LoginUserID = Convert.ToInt32(result);
AdminRights = ???; //how can I get this value from datatable?
UserRights = ???; //how can I get this value from datatable?
this.Close();
}
现在在 form1 中,我想通过 ID 获取 AdminRights 或 UserRights 的值,我有这个代码:
private void button7_Click(object sender, EventArgs e) // Button to Form2
{
Form2 win_form2 = new Form2();
win_form2.ShowDialog();
if (win_form2.loginresult == 1)
{
label4.Text = string.Format("User ID: {0}", win_form2.LoginUserID.ToString()); // Gets and places specific user ID
if (win_form2.UserRights = 0 && win_form2.AdminRights = 1) // Check if the ID has AdminRights
label5.text = string.Format("Rights: {0}", "Admin") // If true, do the following
else if (win_form2.UserRights = 1 && win_form2.AdminRights = 0) // Check if the ID has UserRights
label5.text = string.Format("Rights: {0}", "User") // If true, do the following
}
}
我的数据表:
- 用户 ID (PK 1,1)
- 用户名(字符串)
- 用户密码(字符串)
- AdminRights (int)(值可以是 0 或 1,并且不能与 UserRights 的值相同)
- UserRights (int)(值可以是 0 或 1,并且不能与 AdminRights 的值相同)
那么最后,我如何访问数据表并在 form2 中获取 UserRights 和 AdminRights 值?
注意:我知道我有关于密码和 SQL 注入的非常危险的代码,现在我只想让它工作。
【问题讨论】:
-
警告:您的第一个代码块中的代码很容易受到注入攻击!您需要为您的查询参数化。此外,您的查询暗示您正在存储纯文本密码;这也是一个巨大的担忧。您应该将密码存储为散列和加盐值; 从不作为纯文本。
-
我知道这一点,但是现在我希望它能够工作,我仍在尝试全面了解 SQL。
-
您需要使用
ExecuteReader或Datatable.Load
标签: c# sql-server winforms datatable datatables