用户可以使用Visual C#& amp; SQL

时间:2014-01-26 09:44:31

标签: c# sql login

这是我的用户登录代码。我想将用户输入与SQL匹配。其中emp_ID,密码和用户类型(Admin,employee)应等于用户输入。此代码无法正常运行。因此,当我选择用户类型时,它表示拒绝访问

try
        {
            myconnection.Open();
            cmd = new SqlCommand("select * from loging  where emp_ID = '" + username.Text + "' and password = '" + password.Text + "' and user_type = '"+label4.Text+"'", myconnection);
            myreader = cmd.ExecuteReader();
            int count = 0;
            while (myreader.Read()) 
            {
                count = count + 1;
            }
            if (count == 1 || comboBox1.Text == label4.Text )
            {
                MessageBox.Show("Access Granted");
            }

            else if (count > 1)
            {
                MessageBox.Show("Access denied");
            }
            else
            {
                MessageBox.Show("Access denied");
            }


            myconnection.Close();
        }

2 个答案:

答案 0 :(得分:0)

虽然你还没有解释你所面临的确切问题,但我想建议你一些基本的东西来提供更多的安全性。

建议1:您的SELECT查询对SQL-Injection次攻击开放,因此我建议您使用Parameterised queries来避免它们。

建议2:如果您只想count SELECT次查询返回的行总数,则可以使用以下查询来简化任务:

SELECT COUNT(*) FROM TableName;

上面的查询将返回返回的总行数。

建议3:在您的代码中,您不需要有两个其他块,因为两者都相似。因此,您可以删除其中一个以提高代码的可读性。

注意:正如我已经在评论中提到的那样,如果您可以告诉我们您的代码中Combobox1究竟是什么以及它与label4的关系,那么它会有所帮助我们来解决您的问题。

完整代码:

    try
    {
        myconnection.Open();
        cmd = new SqlCommand("select count(*) from loging  where emp_ID =@emp_ID and password =@password and user_type = @user_type", myconnection);
        cmd.Parameters.AddWithValue("@emp_ID",username);
        cmd.Parameters.AddWithValue("@password",password);
        cmd.Parameters.AddWithValue("@user_type",label4.Text);

        int count = Convert.ToInt32(cmd.ExecuteScalar());            
        if (count == 1 || comboBox1.Text == label4.Text )
        {
            MessageBox.Show("Access Granted");
        }
        else 
        {
            MessageBox.Show("Access denied");
        }
        myconnection.Close();
    }

答案 1 :(得分:0)

一些关于安全的建议:

  • 不要连接SQL查询字符串,而是使用参数来避免SQL注入;
  • 不要使用标准密码文本框,这是一个c#memory-pinning实现,可以保护您免受内存交换密码到磁盘;
  • 不要只计算您获得的行数,但要求数据库向您发送您必须匹配的实际信息;
  • 不要将密码保存在数据库中,用随机盐对抗彩虹攻击;
  • 不要使用Math.Random(),而应使用加密的RandomNumberGenerator类。

也许应该给出2-3个其他建议,但我的眼睛已经流血......