本文介绍了对象引用未设置为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 SqlConnection con = new SqlConnection(Helper.connstr); SqlCommand cmd = new SqlCommand( SELECT UserName FROM LoginInfo WHERE UserName =' + txtUserName.Text + ',con ); con.Open(); string Un = cmd.ExecuteScalar()。ToString(); if (Un == txtUserName.Text) { lblError.Visible = 真; lblError.Text = 有效用户; lblError.ForeColor = System.Drawing.Color.Green; cmd = new SqlCommand( SELECT Passwd FROM LoginInfo WHERE Passwd =' + txtPassword.Text + ',con) ; (THROWS ERROR HERE) string Pwd = cmd.ExecuteScalar()。ToString(); if (Pwd == txtPassword.Text) { } else { lblError.Visible = true ; lblError.ForeColor = System.Drawing.Color.Red; lblError.Text = 无效密码......; } } else { lblError.Visible = 真; lblError.ForeColor = System.Drawing.Color.Red; lblError.Text = 用户不存在; } 我的尝试: 我不明白该怎么办?解决方案 看起来您的第二个(密码)查询不成功。你必须通过捕获异常来处理这种情况(参见上面链接中的示例代码)。 另请注意,您不应该使用此类SQL查询,因为它们容易出现 SQL注入 - 维基百科 [ ^ ]。请改用参数化查询。 参见 SqlCommand.Parameters属性(System.Data.SqlClient) [ ^ ] [/编辑] 您还应该使用单个组合查询传递名称和密码,因为可能有不同的用户具有相同的密码。报告登录错误的常见做法是没有任何关于错误部分的信息,因为这些信息可以帮助攻击者。 SqlConnection con = new SqlConnection(Helper.connstr); SqlCommand cmd = new SqlCommand("SELECT UserName FROM LoginInfo WHERE UserName='" + txtUserName.Text +"'", con); con.Open(); string Un = cmd.ExecuteScalar().ToString(); if (Un == txtUserName.Text) { lblError.Visible = true; lblError.Text = "Valid User"; lblError.ForeColor = System.Drawing.Color.Green; cmd = new SqlCommand("SELECT Passwd FROM LoginInfo WHERE Passwd='" + txtPassword.Text + "'", con); (THROWS ERROR HERE)string Pwd =cmd.ExecuteScalar().ToString(); if (Pwd == txtPassword.Text) { } else { lblError.Visible = true; lblError.ForeColor = System.Drawing.Color.Red; lblError.Text = "Invalid Password..."; } } else { lblError.Visible = true; lblError.ForeColor = System.Drawing.Color.Red; lblError.Text = "User Does Not Exist"; }What I have tried:I donot understand what to do? 解决方案 It looks like your second (password) query is not successful. You must handle such by catching exceptions (see the example code from the above link).Note also that you should never use such SQL queries because they are prone to SQL injection - Wikipedia[^]. Use parametrised queries instead. [EDIT]See SqlCommand.Parameters Property (System.Data.SqlClient)[^] [/EDIT]You should also use a single combined query passing name and password because there may be different users having the same password. It is also common practice to report login errors without any information about the wrong part(s) because those information would help attackers. 这篇关于对象引用未设置为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-18 21:42