查询是否存在行

时间:2012-04-18 13:58:31

标签: vb.net sql-server-2008

我需要知道何时以及是否存在行并且我想使用ExecuteReader吗?

我的代码只是想知道我要去哪里。

Const c_str_SELECT_SQL As String = "SELECT Fails FROM LoginAttacks WHERE IP = ?"

If Not String.IsNullOrEmpty(strPointsDBConnectionString) Then
    objOLEConnection = New OleDbConnection(strPointsDBConnectionString)
    objOLEConnection.Open()
    objOLECommand = New OleDbCommand(c_str_SELECT_SQL, objOLEConnection)
    objIP = objOLECommand.Parameters.Add("@IP", OleDbType.Char)
    objIP.Value = Me.IPAddress

    ' Connect execute update query
    FailedCounts = CInt(objOLECommand.ExecuteScalar())

    If FailedCounts > 0 Then 'need to find way to tell if query worked/found row with ip
        FailedCounts = FailedCounts + 1
        'Did not fail assume worked so go use update function
        IPExist = True 'if not go use insert function
    End If
Else
    Throw New Exception(const_CONNECTION_STRING_ERROR)
End If

更新:

我补充说:

objOLEDataReader = objOLECommand.ExecuteReader()

If objOLEDataReader.HasRows Then
    'Do While objOLEDataReader.Read()
    FailedCounts = CInt(objOLECommand.ExecuteScalar())
    FailedCounts = FailedCounts + 1
    'Did not fail assume worked so go use update function
    IPExist = True 'if not go use insert function
    'Loop
Else
    'none found
End If

objOLEDataReader.Close()

但是,即使有行,我也似乎没有进入IF语句。

1 个答案:

答案 0 :(得分:0)

如果没有数据,则从the documentation ExecuteScalar将返回Nothing。所以你应该先检查一下Nothing是否有行:

Dim FailedCountsObject As Object = objOLECommand.ExecuteScalar()

'need to find way to tell if query worked/found row with ip
If FailedCountsObject IsNot Nothing Then
    FailedCounts = CInt(FailedCountsObject)
    FailedCounts = FailedCounts + 1
    'Did not fail assume worked so go use update function
    IPExist = True 'if not go use insert function
End If