如何找出ExecuteScalar()是dbnull

时间:2018-09-14 05:46:32

标签: vb.net if-statement dbnull executescalar

如何检查ExecuteScalar()的结果是否没有数据?检查是否为空不起作用。

我的代码:

Dim cmdCode As New OracleCommand
cmdCode.Connection = sgcnn
cmdCode.CommandText = "select max(SUBSTR(client_code,4,7)) from CLIENT_INFO where (client_code Like '%' || :SysUser || '%') "
cmdCode.Parameters.Add("@SysUser", OracleDbType.Varchar2).Value = strMessage

'Dim sqlResult As Object = cmdCode.ExecuteScalar()
'If sqlResult Is Nothing Then
'    ' No result found
'    strMessage.Append("0001")
'    txtClientCode.Text = strMessage.ToString
'Else
'    'result found
'    Dim newProdID As Int32 = 0
'    newProdID = Convert.ToInt32(cmdCode.ExecuteScalar())
'    newProdID = newProdID + 1
'    strMessage.Append(newProdID.ToString("0000"))
'    txtClientCode.Text = strMessage.ToString
'End If

2 个答案:

答案 0 :(得分:1)

If sqlResult Is DBNull.Value Then

一旦确定它不是NULL,就不要再调用ExecuteScalar。您已经得到了结果,请使用它。此外,它已经是Integer,因此无需进行转换。刚刚投放:

Dim newProdID = CInt(sqlResult) + 1

答案 1 :(得分:0)

        If IsDBNull(cmdCode.ExecuteScalar()) Then
        '    ' No result found
        '    strMessage.Append("0001")
        '    txtClientCode.Text = ""
    Else
        '    'result found
        '    Dim newProdID As Int32 = 0
        '    newProdID = Convert.ToInt32(cmdCode.ExecuteScalar())
        '    newProdID = newProdID + 1
        '    strMessage.Append(newProdID.ToString("0000"))
        '    txtClientCode.Text = strMessage.ToString
    End If