简体   繁体   English

C#和SQL Server:表的条件语句

[英]C# and SQL Server : conditional statement for tables

I have a program that uses administrator and employee login. 我有一个使用管理员和员工登录的程序。 I have two tables in SQL Server named Admin and Employee . 我在SQL Server中有两个表,分别为AdminEmployee

I only have one login window. 我只有一个登录窗口。 I have two forms AdminForm and EmpForm . 我有两种形式AdminFormEmpForm When username and password are entered, I want to read the two tables. 输入用户名和密码后,我要阅读两个表。

  • If username and password belongs to the table Admin , then it will show the AdminForm 如果用户名和密码属于表Admin ,则它将显示AdminForm
  • but when username and password belong to table Employee , it will show the EmpForm 但是当用户名和密码属于表Employee ,它将显示EmpForm

I'm new to SQL Server. 我是SQL Server的新手。 Is there anyway Was it possible? 反正有可能吗? As of now, this my code: 到目前为止,这是我的代码:

private void btnLogin_Click(object sender, EventArgs e)
{    
    using (var connect = sqlcon.getConnection())
    {
         using (SqlCommand cmd = new SqlCommand("SELECT * FROM administrator WHERE username = @username AND password = @password"))
         {
              cmd.Connection = connect;
              connect.Open();
              cmd.Parameters.Add("@cusername", SqlDbType.Char).Value = tbUsername.Text;
              cmd.Parameters.Add("@cpassword", SqlDbType.Char).Value = tbPassword.Text;
              using (SqlDataReader re = cmd.ExecuteReader())
              {
                 if (re.Read())
                 {
                 }
                 else
                 {
                 }                               
             }                        
        }
    }
}

The schema is wrong. 模式错误。 Combine the two tables into a single Users table with an additional column indicating which role the user belongs to. 将两个表合并为一个Users表,并在表中增加一列,以表明用户属于哪个角色。

You need 2 sql queries which take parameters user name and password, one query return objects of admin another query return object employee if inserted parameters are correct, otherwise they return null. 您需要2个sql查询,它们使用参数用户名和密码,如果插入的参数正确,则一个查询返回admin的对象,另一个查询返回对象employee,否则返回null。

Try to initialize objects of Admin and Employee with results of those 2 queries. 尝试使用这两个查询的结果初始化Admin和Employee的对象。 Than test 比测试

if(admin != null) open AdminForm. if(admin != null)打开AdminForm。 else if(employee != null) open EmpForm. else if(employee != null)打开EmpForm。 else - show message incorrect user name or/and password. else -显示消息错误的用户名或密码。

Soner Gönül is right try using hashing with or without salt for not storing password in clear text. SonerGönül正确地尝试使用带有或不带有盐的哈希来不以明文形式存储密码。

Your query can work like this: 您的查询可以像这样工作:

Select [EntityType] =1 , SurrogateKey = EmployeeKey, LastName, FirstName from dbo.Employee where (blah blah blah)
UNION ALL
Select [EntityType] = 2, SurrogateKey = AdminKey, LastName, FirstName from dbo.Admin where (blah blah blah)

Then you'll have a way to distinguish the rows....and you can make a decision if you get 2 rows back. 然后,您将有一种方法来区分行...。如果可以退回两行,则可以做出决定。 EmployeeKey and AdminKey (whatever your PK names are) would have to be the same datatype. EmployeeKey和AdminKey(无论您的PK名称是什么)都必须是相同的数据类型。 (LastName and FirstName as well, you can only UNION/UNION ALL if all the datatypes match. (以及LastName和FirstName,如果所有数据类型都匹配,则只能UNION / UNION ALL。

.............. ..............

Having said that..........you have "mixed" alot of concerns. 话虽如此……..您已经“混合”了许多担忧。 Create a DataLayer that returns some kind of POCO object that has the necessary values. 创建一个DataLayer,它返回某种具有必要值的POCO对象。 A button_click and a SqlConnection should not be in the same code. button_click和SqlConnection不应使用相同的代码。

pubic class LoginResult()
{
public int EntityType {get;set;}
public int SurrogateKey {get;set;}
public string LastName{get;set;}
public string FirstName{get;set;}
}


public interface IAccountManager
{
LoginResult AttemptLogin (string userName, string password)
}
public class IAccountManager() : IAccountManager
{
public LoginResult AttemptLogin (string userName, string password)
{
// put your SqlConnection/SqlReader code here
// do not put any "logic" "if checks" etc....the concern here is to only create the object
}
}

That's a little better to separate concerns. 分开关注点要好一些。 Google "C# Layers" for more discussion. 谷歌“ C#层”的更多讨论。

As others have said, this is not the correct way to do usernames / passwords. 正如其他人所说,这不是正确的用户名/密码方式。 But the answer to your question would be to use a union, like: 但是,您的问题的答案将是使用联合,例如:

         using (SqlCommand cmd = new SqlCommand("SELECT 1 as IsAdmin, * 
FROM administrator 
WHERE username = @username AND password = @password 
    UNION ALL 
SELECT 0 as IsAdmin, * 
FROM employees 
WHERE username = @username AND password = @password "))

I used rights for admin and employee and coded it. 我使用了管理员和员工的权限并将其编码。 Thanks for all idea! 感谢您的所有想法! For someone need it, please refe to the code below. 如果有人需要它,请参考以下代码。 Don't forget to encrypt your passwords. 不要忘记加密密码。

 private void btnLogin_Click(object sender, EventArgs e)
    {
        using (var connect = sqlcon.getConnection())
        {
            using (SqlCommand cmd = new SqlCommand("SELECT rights FROM employee WHERE username = @username AND password = @password"))
            {
                cmd.Connection = connect;
                connect.Open();
                cmd.Parameters.Add("@username", SqlDbType.Char).Value = tbUsername.Text;
                cmd.Parameters.Add("@password", SqlDbType.Char).Value = tbPassword.Text;
                //SqlDataReader re = cmd.ExecuteReader();
                string aeRights = (string)cmd.ExecuteScalar();

                if (aeRights == "1")
                {
                    frmAdmin frmA = new frmAdmin();
                    frmA.Show();
                    this.Hide();
                }

                else if (aeRights == "2")
                {
                    frmEmp frmE = new frmEmp();
                    frmE.Show();
                    this.Hide();
                }

                else if (string.IsNullOrEmpty(aeRights))
                {
                    MessageBox.Show("Invalid username or password! Please try again", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }              
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM