ASP.NET 无法 select 和更新

ASP.NET unable select and Update

protected void btnLogin_Click(object sender, EventArgs e)
{

    SqlConnection conn = new SqlConnection("Data Source=MCDU11;Initial Catalog=VisitorManagement;Integrated Security=True");

    SqlCommand cmd = new SqlCommand("SELECT * FROM SecurityUser WHERE Username = '" + txtUsername.Text.Trim() + "' AND "
                                        + "Password='" + Encrypt(txtPassword.Text.Trim()) + "'" , conn);

    SqlCommand cmd1 = new SqlCommand("update SecurityUser set LoginOn ='" + DateTime.Now + "' , " + "WHERE Username ='" + txtUsername.Text.Trim() + "'", conn);
    conn.Open();

    SqlDataReader dr;

    dr = cmd.ExecuteReader();


    if (dr.Read())
    {

        Session["Username"] = txtUsername.Text;
        Session["Id"] = dr["Id"].ToString();
        cmd1.ExecuteNonQuery();
        Response.Redirect("SecurityHome.aspx");

    }
    else
    {
        lblError.Text = "Either username and/or password is wrong. Please try again!";
    }

    dr.Close();
    conn.Close();


}

这是我的错误

"An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code

Additional information: There is already an open DataReader associated with this Command which must be closed first."

"There is already an open DataReader associated with this Command which must be closed first."

异常消息非常清楚,在关闭原始 DataReader 之前,您无法执行连接的任何命令(另一个 DataReader、NonQuery ...)。 在您的情况下,抛出异常的代码是

cmd1.ExecuteNonQuery();

您应该将代码提取到两个方法中,第一个将从数据库中获取数据,第二个将在第 1 步成功时进行更新。

演示用:

private static string ConnectionString = "Data Source=MCDU11;Initial Catalog=VisitorManagement;Integrated Security=True";

protected string GetLoggedUserId(string username, string password) {
    var id = string.Empty;
    using(var conn = new SqlConnection(ConnectionString) {
        var cmd = new SqlCommand("SELECT * FROM SecurityUser WHERE Username = '" + username + "' AND "
                                        + "Password='" + password)  + "'" , conn);
        conn.Open();
        using(var reader = cmd.ExecuteReader()){
            if(reader.Read()){
                id = reader["Id"].ToString();
            }   
        }
    } 
    return id;
}

protected string UpdateLoggedUser(string username) {
    using(var conn = new SqlConnection(ConnectionString) {
        var cmd = new SqlCommand("update SecurityUser set LoginOn ='" + DateTime.Now + "' , " + "WHERE Username ='" + username + "'", conn);
        conn.Open();
        cmd.ExecuteNonQuery();
    } 
}

protected void btnLogin_Click(object sender, EventArgs e) {

    var loggedId = GetLoggedUserId(txtUsername.Text.Trim(),Encrypt(txtPassword.Text.Trim()));

    if(!string.IsNullOrWhiteSpace(loggedId))
    {
        UpdateLoggedUser(txtUsername.Text.Trim());
        Response.Redirect("SecurityHome.aspx");
    }
    else
    {
        lblError.Text = "Either username and/or password is wrong. Please try again!";
    }   
}

根据 MSDN:https://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.80).aspx

用户数据适配器。它比 DataReader 更快,而且它也是面向断开连接的架构

    string connString = "Data Source=MCDU11;Initial Catalog=VisitorManagement;Integrated Security=True";

    SqlCommand cmd = new SqlCommand("SELECT * FROM SecurityUser WHERE Username = '" + txtUsername.Text.Trim() + "' AND "
                                        + "Password='" + Encrypt(txtPassword.Text.Trim()) + "'" , conn);

    SqlCommand cmd1 = new SqlCommand("update SecurityUser set LoginOn ='" + DateTime.Now + "' , " + "WHERE Username ='" + txtUsername.Text.Trim() + "'", conn);
   using (SqlConnection conn = new SqlConnection(connString))  
{

    using (SqlDataAdapter a = new SqlDataAdapter(
            cmd, conn))
    {
                DataTable t = new DataTable();
                a.Fill(t);

       if (t.Rows.Count > 0)
       {

        Session["Username"] = txtUsername.Text;
        Session["Id"] = t[0]["Id"].ToString();
        cmd1.ExecuteNonQuery();
        Response.Redirect("SecurityHome.aspx");

       }
       else
       {
        lblError.Text = "Either username and/or password is wrong. Please try again!";
       }

   }

   }

尝试在您的连接中添加 MultipleActiveResultSets=True 作为

 SqlConnection conn =
new SqlConnection("Data Source=MCDU11;
Initial Catalog=VisitorManagement;Integrated Security=True;MultipleActiveResultSets=True");

    SqlCommand cmd1 = 
new SqlCommand("update SecurityUser set LoginOn ='" + DateTime.Now + "' 
WHERE Username ='" + txtUsername.Text.Trim() + "'",conn);