使用.Nest()或.Read()时SQLDataReader出错

时间:2018-07-19 10:23:28

标签: c# asp.net visual-studio sqldatareader

我正在通过SQLDataReader从MSSQL检索某些信息,但是在调试它时,我注意到在某些情况下,读者会清除错误“ Enumeration没有结果”的结果视图,请参见屏幕快照
Before Running passing Read(),
After passing read()


这是我的代码,该错误发生在getActiveUsers()方法上。 getDatabases()可以正常工作。 有人可以帮我吗?欢呼

 public partial class automation : System.Web.UI.Page
{
    SqlConnection con;
    static List<ActiveUsers> activeUsers = new List<ActiveUsers>();
    protected void Page_Load(object sender, EventArgs e)
    {
        ASPxGridView1.DataSource = activeUsers.ToList();

    }
    public List<ActiveUsers> getDatabases()
    {

        //passing query
        string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name  FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
        //creating connection
        string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
        con = new System.Data.SqlClient.SqlConnection(sqlconn);
        var cmd = new SqlCommand(SqlQuery, con);
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
         List<ActiveUsers> results = new List<ActiveUsers>();
        if (reader.Read())
        {
            while (reader.Read())
            {
                ActiveUsers company = new ActiveUsers();
                company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
                company.ClientName = String.Format("{0}", reader["Name"]);
                results.Add(company);
            }
        }
        con.Close();
        return results;
    }

    public void getActiveUsers()
    {

        activeUsers.Clear();
        List<ActiveUsers> Databases= getDatabases();
        SqlConnection conn = new SqlConnection();
        string SqlQuery = "select [disabled], [ADMN_Users1].[Record_Id] ,[ADMN_Users].[User_Id] from admn_Users1  inner join [ADMN_Users] on [ADMN_Users1].[record_Id] = [ADMN_Users].[Record_Id] Where [disabled] & 0x2 = 0 ";

        for (int i = 0;i < Databases.Count;i++)
        {

            conn.ConnectionString =
            "Data Source=MAXSQLCLUS01;" +
            "Initial Catalog=" + Databases[i].ToString()+";"+
            "User id=sa;" +
            "Password=Max1m1zer;";
            var cmd = new SqlCommand(SqlQuery, conn);
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            int NumberOfUsersCounter = 0 ;
            //TODO Select Enabled users
            if (reader.Read())
            {

                while (reader.Read())
                {
                    string user = String.Format("{0}", reader["User_Id"]);
                    //logic to remove system users

                    if (user.Equals("master", StringComparison.CurrentCultureIgnoreCase))
                    {


                    }
                    else
                    if (user.Equals("emailuser", StringComparison.CurrentCultureIgnoreCase))
                    {

                    }
                    else
                    if (user.Equals("webuser", StringComparison.CurrentCultureIgnoreCase))
                    {


                    }
                    else
                    {

                        NumberOfUsersCounter++;
                    }

                }
                ActiveUsers newEntry = new ActiveUsers();

                newEntry.NumberActiveUsers = NumberOfUsersCounter.ToString();
                newEntry.DatabaseName = Databases[i].DatabaseName.ToString();
                newEntry.ClientName = Databases[i].ClientName.ToString();
                activeUsers.Add(newEntry);

            }
            conn.Close();

            //Add to ActiveUsers list


        }



        ASPxGridView1.AutoGenerateColumns = true;

        ASPxGridView1.DataSource = activeUsers.ToList();
        ASPxGridView1.DataBind();

    }

    protected void ASPxButton1_Click(object sender, EventArgs e)
    {

        getActiveUsers();
    }

    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        ASPxGridView1.DataBind();
        ASPxGridViewExporter1.Landscape = true;
        ASPxGridViewExporter1.FileName = "User Count Report";
        ASPxGridViewExporter1.WriteXlsToResponse();

    }
}

}

2 个答案:

答案 0 :(得分:3)

if (reader.Read())
{
    while (reader.Read())
    {
       ActiveUsers company = new ActiveUsers();
       company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
       company.ClientName = String.Format("{0}", reader["Name"]);
       results.Add(company);
    }
}

使用此

if (reader.HasRows)
{
    while (reader.Read())
    {
       ActiveUsers company = new ActiveUsers();
       company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
       company.ClientName = String.Format("{0}", reader["Name"]);
       results.Add(company);
    }
}

您的条件是否错误

if(reader.Read()) ==> is Wrong 

Read()不返回布尔值

使用HasRows在SQLDataReader中检查行

答案 1 :(得分:1)

您正在跳过第一个结果。 if (reader.Read()) { while(reader.Read()) {....删除封闭的if,它所做的只是看是否有一行并检索它,但随后您不读它,而是在if中再次这样做,因此总是丢弃第一个结果。

public List<ActiveUsers> getDatabases()
{
    //passing query
    string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name  FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
    //creating connection
    string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;

    using(con = new System.Data.SqlClient.SqlConnection(sqlconn))
    using(var cmd = new SqlCommand(SqlQuery, con))
    {
        con.Open();
        using(SqlDataReader reader = cmd.ExecuteReader())
        {
            List<ActiveUsers> results = new List<ActiveUsers>();
            while (reader.Read())
            {
                ActiveUsers company = new ActiveUsers();
                company.DatabaseName = reader.GetString(0);
                company.ClientName = reader.GetString(1);
                results.Add(company);
            }
        }
    }
    return results;
}

旁注:

  • company.DatabaseName = String.Format("{0}", reader["WorkspaceName"])最好写成company.DatabaseName = reader.GetString(0)。下一行也一样。无需使用string.Format,您可以在查询中指定列和顺序,因此请使用序数索引,以便获取本机值。
  • 我建议您将SqlConnectionSqlDataReader包装在using块中,以确保使用后即使在发生异常的情况下也将它们关闭/处置。