执行标量不能传递密码文本框,抛出null异常

时间:2015-11-06 08:39:20

标签: c# sql asp.net ado.net

代码确实连接到数据库并实际检查用户名(数字),然后在必须验证密码并抛出空引用时运行异常

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Intellicell_CallCentreConnectionString"].ConnectionString);
        conn.Open();

        string checkuser = "SELECT COUNT(*) FROM Debtors WHERE MobilePhone='" + txtMobilePhone.Text + "'";
        SqlCommand cmd = new SqlCommand(checkuser, conn);

        int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
        conn.Close();
        if (temp == 1)
        {
            conn.Open();
            string CheckPasswordQuery = "SELECT IDNumber from Debtors WHERE MobilePhone='" + txtPassword.Text + "'";
            SqlCommand passCmd = new SqlCommand(CheckPasswordQuery, conn);
            string password =  passCmd.ExecuteScalar().ToString().Replace(" ","");
            conn.Close();
            if (password == txtPassword.Text)
            {
                Session["New"] = txtMobilePhone.Text;
                Response.Write("Password is correct!");
                Response.Redirect("Home.aspx");
            }
            else
            {
                Response.Write("Password is not correct!");
            }
        }
        else
        {
            Response.Write("Please Provide valid Login details!");
        }
    }
}

它在线

string password =  passCmd.ExecuteScalar().ToString().Replace(" ",""); 

它破了。

3 个答案:

答案 0 :(得分:0)

我建议你如果想写sql adhoc,请使用string.format

很干净

string checkuser = string.Format("SELECT COUNT(*) FROM Debtors WHERE MobilePhone={0},txtMobilePhone.Text);

其次,您可以使用using syntax来正确清理连接

答案 1 :(得分:0)

我认为,在第二个sql中你使用的是txtPassword.Text而不是txtMobilePhone.Text

答案 2 :(得分:0)

问题是为什么你得到null execption,请看:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx

总之,如果没有找到行,ExecuteScaler会返回一个null(不是DBNull),passCmd.ExecuteScalar().ToString().Replace(" ",""); null将其作为null.ToString()

重新引用

你的全局逻辑看起来很有缺陷,很难确切地建议做什么,但是passCmd.ExecuteScalar()?.ToString().Replace(" ","")会抑制这种异常。