【问题标题】:SQLDataReader bugging while using .Nest() or .Read()使用 .Nest() 或 .Read() 时出现 SQLDataReader 错误
【发布时间】:2018-07-19 18:41:09
【问题描述】:

我正在通过 SQLDataReader 从 MSSQL 中检索一些信息,但在调试它时,我注意到在某些情况下,阅读器会清除结果视图并显示错误“枚举未产生结果”,请参阅屏幕截图
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();

    }
}

}

【问题讨论】:

  • 一个不相关的错误:您正在跳过第一个结果。 if (reader.Read()) { while(reader.Read()) {...。删除封闭的if,它所做的只是查看是否有一行并检索它,但你不读取它,而是在 if 中再次执行它,所以第一个结果总是被丢弃。
  • 屏幕警告你——扩展将枚举可枚举。 SqlDataReader 只能枚举一次,因为它只读取数据库一次。不要使用调试器查看它,除非您可以重新启动调试会话。
  • 另一个旁注:company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]) 最好写成company.DatabaseName = reader.GetString(0)。下一行也是如此。无需使用 string.Format 并且您正在指定查询中的列和顺序,因此请使用序数索引以获取本机值。
  • 我会试试你的建议@Igor
  • 旁注 3:最后,我建议您将 SqlConnectionSqlDataReader 包装在 using 块中,以确保它们在使用后即使出现异常也能关闭/处理。跨度>

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


【解决方案1】:
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 条件错误

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

Read() 不返回布尔值

使用 HasRows 检查 SQLDataReader 中的行

【讨论】:

    【解决方案2】:

    您正在跳过第一个结果。 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 块中,以确保它们在使用后即使出现异常也能关闭/处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2018-10-24
      • 2016-10-28
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 2017-12-26
      相关资源
      最近更新 更多