CQ中的用户代码未对SQLException进行处理

Shr*_*ree 0 c# sql asp.net sql-server-2005

我试着检查用户是否存在.我尝试:

public static bool GetUser(string tblName, string UserName,string Password,string Usertype)
        {
            try
            {

                using (SqlConnection con = Connection.GetConnection())
                {
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                       cmd.CommandText = "select count(UserName) from " + tblName + " where Password=" + Password + " and usertype=" + Usertype + " and username="+ UserName + "";
                        object obj = cmd.ExecuteScalar();
                        if (obj != null)
                            return true;
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
Run Code Online (Sandbox Code Playgroud)

当我调用此方法时出现以下错误.
我的错误
连接成功建立,我这样称呼这个方法.

bool Check = UserLogin.GetUser("OnlineCertificationLogin", "admin", "admin", "Admin");
Run Code Online (Sandbox Code Playgroud)

我的表结构是

我的表结构
无法找到我的错误.谢谢.

Jon*_*eet 6

您没有引用这些值,因此您的SQL最终会:

select count(UserName) from OnlineCertificationLogin
where Password=admin and usertype=admin and username=Admin
Run Code Online (Sandbox Code Playgroud)

不要通过添加引号来解决此问题.您的代码将适用于给定的示例,但您很容易受到SQL注入攻击.相反,您应该使用参数化查询来解决此问题 - SqlCommand.Parameters有关详细信息和示例,请参阅参考资料.

虽然你不能参数表名,你应该确保它只有不断通过受信任的代码来-不是通过用户输入,例如,否则你又得到了完全一样的SQL注入的问题.

请注意,您也不应该以明文形式存储密码.

我强烈建议你掌握一本关于安全性的书 - 开始ASP.NET安全可能会在你的街道上.(我有一份副本,但我承认还没读过多少 - 我听过巴里谈论安全问题,而且他非常清楚地解释了这一点.)