将密码用户输入与数据库进行比较

时间:2012-10-12 05:04:03

标签: c# asp.net

我是asp.net的新手,我正在编写一个用于学习asp.net的登录页面,这是脚本的错误。当我输入的密码只包含英文字母时,没有错误,但是当我输入的密码包含数字/仅数字,例如abc123或123时,第28行会产生错误,有人知道有什么问题吗?

感谢

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 26:             string cmdStr2 = "Select Password from [user] where UserName = '" + TextBox2.Text + "'";
Line 27:             SqlCommand pass = new SqlCommand(cmdStr2, con);
Line 28:             string password = pass.ExecuteScalar().ToString();
Line 29:             
Line 30:             Label1.Text = password;

Source File: c:\inetpub\web1\Login.aspx.cs    Line: 28 

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   Login.Button1_Click(Object sender, EventArgs e) in c:\inetpub\web1\Login.aspx.cs:28
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

2 个答案:

答案 0 :(得分:1)

  

Return Value of ExecuteScalar can be null

     

类型:System.Object

     

结果中第一行的第一列   如果结果集,则设置或空引用(在Visual Basic中为Nothing)   是空的。最多返回2033个字符。

因此,在执行任何操作之前,您需要先检查nullExecuteScalar()

object retVal = pass.ExecuteScalar();
string data = "";
if(retVal != null)
  data = retVal.ToString();

注意事项

  • 要登录用户,请同时检查密码和用户名,例如WHERE username=@username AND password=@password。如果返回记录,则用户的凭证有效,否则它们不匹配
  • 因SQL注入而使用参数化变量:What is SQL injection?

    string cmdStr2 = "Select 1 from [user] where UserName = @Username and Password=@Password";
    SqlCommand command = new SqlCommand(cmdStr2, con);
    command.Parameters.AddWithValue("@Username", Username);
    command.Parameters.AddWithValue("@Password", Password);
    

答案 1 :(得分:0)

首先,您需要使用Parameters提供值。不要只是将值嵌入字符串中。不要使用ExecuteScalar()。使用SqlDataAdapter获取返回的用户信息并检查DataTable中的密码如果ExecuteScalar()没有返回值,则.ToString()不起作用并抛出null异常是什么你得到了。您需要执行“select * from user where username = @username”而不是按密码搜索。然后将该用户名的密码与用户提供的密码进行匹配。

相关问题