Skip to main content
 首页 » 编程设计

c#之“不存在数据时读取无效”错误

2024年02月05日10txw1958

我有这个代码块:

using (SqlConnection con2 = new SqlConnection(str2)) 
{ 
    using (SqlCommand cmd2 = new SqlCommand(@"SELECT * FROM VW_MOS_DPL_AccountValidation WHERE CUST_NUM = @CNum", con2)) 
    { 
        con2.Open(); 
 
        cmd2.Parameters.AddWithValue("@CNum", TBAccountNum.Text); 
 
        using (SqlDataReader DT2 = cmd2.ExecuteReader()) 
        { 
            // If the SQL returns any records, process the info 
            if (DT2.HasRows) 
            { 
                // If there's a BusinessID (aka Business Type), fill it in 
                string BizID = (DT2["Business_ID"].ToString()); 
                if (!string.IsNullOrEmpty(BizID)) 
                { 
                    DDLBustype.SelectedValue = BizID; 
                } 
            } 
        } 
        con2.Close(); 
    } 
} 

当它到达线路时

string BizID = (DT2["Business_ID"].ToString()); 

它抛出一个错误:

Invalid attempt to read when no data is present.

如果没有数据,为什么会通过if (DT2.HasRows)?

请您参考如下方法:

你需要打电话

if(DT2.Read())  
 .... 

在继续从 DataReader 读取数据之前。

HasRows只告诉您 SqlDataReader 包含数据,但 SqlDataReader 一次从连接加载一条记录。因此,每次尝试从 SqlDataReader 中提取数据时,都应先调用 Read将 SqlDataReader 定位在通过连接返回的第一条记录上。

并且,因为如果调用能够读取记录,Read 方法返回 true,您可以用类似这样的方法替换对 HasRows 的调用

    using (SqlDataReader DT2 = cmd2.ExecuteReader()) 
    { 
        // If the SQL returns any records, process the info 
        while(DT2.Read()) 
        { 
            // If there's a BusinessID (aka Business Type), fill it in 
            string BizID = (DT2["Business_ID"].ToString()); 
            if (!string.IsNullOrEmpty(BizID)) 
            { 
                DDLBustype.SelectedValue = BizID; 
            } 
        } 
    } 

顺便说一下,如果 BusinessID 可能为 NULL,那么您需要进行不同的测试以避免异常问题

int bizColIndex = DT2.GetOrdinal("Business_ID"); 
string BizID = (DT2.IsDBNull(bizColIndex) ? string.Empty : DT2.GetString(bizColIndex)); 
if (!string.IsNullOrEmpty(BizID)) 
{ 
    DDLBustype.SelectedValue = BizID; 
}