【问题标题】:Conversion from type 'DBNull' to type 'Double' is not valid when returns empty data返回空数据时,从“DBNull”类型到“Double”类型的转换无效
【发布时间】:2016-03-08 14:38:59
【问题描述】:

我有一个包含复杂查询的页面。查询正常工作,但只要有 null 或空字符串,就会引发此错误。

从“DBNull”类型到“Double”类型的转换无效。

这是我的代码

If Not Me.IsPostBack Then
            Dim dt As DataTable = Me.GetData("SELECT (`behaviour`+`treatment`+`charges`+`information`+`hygine`+`admission`)/6 AverageRating, COUNT(ID) RatingCount from ratings WHERE hospitalID Like '%" + var2 + "%';")
            avg.Text = FormatNumber(CDbl(dt.Rows(0)("AverageRating")), 1)
            totalVotes.Text = String.Format(dt.Rows(0)("RatingCount"))
        End If

avg.text 在页面加载时从 db 获取值

【问题讨论】:

  • 要么在强制转换前检查 null,要么修复你的 SQL 语句以将 NULL 替换为 0。并将字符串连接替换为参数化查询以避免 SQL 注入攻击

标签: mysql asp.net vb.net


【解决方案1】:

将您的查询更改为,

SELECT (isnull(`behaviour`,0)+isnull(`treatment`,0)+isnull(`charges`,0)+isnull(`information`,0)+isnull(`hygine`,0)+isnull(`admission`,0))/6 AverageRating, COUNT(ID) RatingCount from ratings

【讨论】:

    【解决方案2】:

    在您的 SQL 中使用 isnull 函数。

    示例:选择名称,isnull(rating,0)

    如果 rating=null 则 sql 将返回 0

    【讨论】:

      【解决方案3】:

      Double.TryParse(text, value) 最擅长测试

          If Not Me.IsPostBack Then
          Dim testDouble as Double
          Dim dt As DataTable = Me.GetData("SELECT (`behaviour`+`treatment`+`charges`+`information`+`hygine`+`admission`)/6 AverageRating, COUNT(ID) RatingCount from ratings WHERE hospitalID Like '%" + var2 + "%';")
      
          If Double.TryParse((dt.Rows(0)("AverageRating")), testDouble) Then
              ' text is convertible to Double, and testDouble contains the Double value now'
              avg.Text = FormatNumber(testDouble, 1)
          Else
              ' Cannot convert text to Double'
          End If
              totalVotes.Text = String.Format(dt.Rows(0)("RatingCount"))
          End If
      

      【讨论】:

        【解决方案4】:

        使用扩展方法DataRowExtensions.Field Method (DataRow, String)

        来自文档:

        如果指定DataColumn的值为null且T为引用 类型或可空类型,返回类型将为空。

        If Not Me.IsPostBack Then
            Dim dt As DataTable = Me.GetData("SELECT ....")
            Dim avgValue As Double? = dt.Rows(0).Field(Of Double?)("AverageRating")
            If avgValue.HasValue = True Then
                avg.Text = avgValue.Value.ToString()
            Else
                avg.Text = "no value"
            End If
        
        End If
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-10
          • 2012-11-19
          • 2011-10-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多