executescalar:对象不能从 DBNull 转换为其他类型

executescalar: Object cannot be cast from DBNull to other types

我在 运行 程序期间没有 data/value 时遇到问题,我收到以下错误:

Object cannot be cast from DBNull to other types.

我尝试使用 if dr.hasrow() 验证它,但我仍然遇到错误。

drqry = "SELECT max(num) FROM tbCVinfo WHERE cvno LIKE '%" & cvstr & "%'"

cmd2.CommandText = drqry
cmd2.Connection = con

Dim result As String = ""

cv = Convert.ToInt32(cmd2.ExecuteScalar())
'''''''''in this section I'm getting the error.

cv = cv + 1
If cv >= 0 And cv <= 9 Then
  ...............
Else
    cn = "0001"
End If
cn = result

cvno = cn

解决此问题的一种简单方法是检查返回值是否为 DBNull:

Dim cv As Integer
Dim queryResult = cmd2.ExecuteScalar()
If IsDBNull(queryResult) Then
    ' No matching records. Do something about it.
Else
    cv = DirectCast(queryResult, Integer)
End If