executioncalar:无法将对象从DBNull转换为其他类型

时间:2018-05-17 01:08:25

标签: mysql vb.net executescalar

在运行程序期间没有数据/值被提取时,我遇到了问题,我收到以下错误:

  

无法将对象从DBNull强制转换为其他类型。

我尝试使用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

2 个答案:

答案 0 :(得分:0)

解决此问题的一种简单方法是检查返回的值是否为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

答案 1 :(得分:0)

可以为c#executescalar编写代码吗?

SqlCommand smd = new SqlCommand("Select Min(GidenEvrakSira) FROM GidenEvrak Where UserID is null", con);

minum = Convert.ToInt32(smd.ExecuteScalar());