【问题标题】:Operator '=' is not defined for type 'DBNull' and string "True". VB.net [duplicate]没有为类型“DBNull”和字符串“True”定义运算符“=”。 VB.net [重复]
【发布时间】:2015-04-09 07:21:08
【问题描述】:

使用下面给出的代码时显示一个错误。错误是:Operator '=' is not defined for type 'DBNull' and string "True"。帮助我找到合适的解决方案。谢谢。

代码:

cmd1.CommandText = "select * FROM attendance where academic_year='" & yearTextBox.Text & "' and School_Name='" & courseDropDownList.Text & "' and Class='" & semesterDropDownList.Text & "' and batch='" & batchDropDownList.Text & "' and hour='" & DropDownList6.Text & "' and date_present='" & TextBox1.Text & "'"
sdr1 = cmd1.ExecuteReader
While sdr1.Read
  dr("student_name") = sdr1("student_name")
  dr("rollnumber") = sdr1("roll_number")
  dr("comment") = sdr1("comment")
Dim status As String = ""
  If sdr1("present") = "True" Then // ***Error popup here***
     status = "Present"
  ElseIf sdr1("Absent") = "True" Then
     status = "Absent"
  ElseIf sdr1("od") = "True" Then
     status = "OD"
  End If
  If sdr1("late") = "True" Then
     dr("status_late") = ", Latecomer"
  End If
     dr("status") = status
     dt.Rows.Add(dr)
     dr = dt.NewRow
End While
sdr1.Close()

【问题讨论】:

  • 打破并看看有什么值是sdr1("Present")。如果它为空,请在此处使用.tostring
  • 或在使用比较运算符之前检查Isdbnull

标签: vb.net


【解决方案1】:

当 SQL 可以为您完成工作时,您为什么要通过代码费力地这样做:

select
    student_name,
    roll_number,
    comment,
    CASE
       WHEN present='true' THEN 'present'
       WHEN absent ='true' THEN 'absent'
       WHEN od='true' THEN 'od'
    END as status,
    CASE
       WHEN late ='true' THEN ', Latecomer'
    END as status_late
FROM attendance where academic_year=@year

并且还切换到使用parameterized 查询来提供@year,而不是一起构造字符串。

如果您进行上述更改,您还可以使用结果集直接切换到filling 您的DataTable,而不是使用ExecuteReader 并循环和复制结果。

【讨论】:

  • 问题是,很多程序员不懂SQL,然后在客户端做模糊逻辑
【解决方案2】:

这意味着检索到的值之一是数据库中的NULL,因此您将获得DBNull 类型的值。你应该首先使用.IsDBNull检查检索到的值是否为NOT NULL,然后你可以使用=进行比较。

【讨论】:

    【解决方案3】:

    其实,从数据库中读取数据的时候,一定要保证读取的值是可空的或者强制的。

    对于 Nullable 值,您不能将其设置为例如字符串。 所以,从数据库中读取数据的最佳方式是,在设置值之前需要检查IsDBNull,如下;

    If (sdr1("present") IsNot DBNull.Value) AndAlso sdr1("present") = "True" Then 
         status = "Present"
    ElseIf (sdr1("Absent") IsNot DBNull.Value) AndAlso sdr1("Absent") = "True" Then
         status = "Absent"
    ElseIf (sdr1("od") IsNot DBNull.Value) AndAlso sdr1("od") = "True" Then
         status = "OD"
    End If
    
    If (sdr1("late") IsNot DBNull.Value) AndAlso sdr1("late") = "True" Then
         dr("status_late") = ", Latecomer"
    End If
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      相关资源
      最近更新 更多