【问题标题】:Why is my reader stuck in infinite loop [closed]为什么我的读者陷入无限循环[关闭]
【发布时间】:2015-08-19 00:57:31
【问题描述】:

谁能解释一下为什么会陷入无限循环?我把它放在一个按钮下,效果很好。但是当我把它放在一个类中并实例化这个类时,它就会陷入无限循环。我认为它卡在循环中,因为当我添加断点时,它不会比循环内部更进一步。它甚至没有通过“End While”,但是如果我将此代码放在 ASP.NET 中的按钮单击下,它就可以正常工作。我究竟做错了什么?

请不要批评我向数据库传递值的方式是“SQL 注入”,因为这不会成为公开的事情,我很清楚这一点。

Imports System.Data
Imports System.Data.SqlClient


    'Step 1: Select the device ID
    Function SelectDevice(d As String, b As String, m As String, o As String) As String

        ' Try

        'Connect to database
        Dim xcitoDBConnection As SqlConnection
        xcitoDBConnection = New SqlConnection("Data Source=NOTDISPLAYED;" + "Initial Catalog=NOTDISPLAYED;" + "Integrated Security=True")
        Dim GetDeviceID As String = "SELECT DISTINCT(Identifier) FROM Support.Devices WHERE DeviceType='" & d & "' AND Brand = '" & b & "' AND Model = '" & m & "' AND OS = '" & o & "'"
        Dim command As SqlCommand = New SqlCommand(GetDeviceID, xcitoDBConnection)

        xcitoDBConnection.Open()
        'command.ExecuteScalar()

        Dim reader As SqlDataReader
        reader = command.ExecuteReader(CommandBehavior.CloseConnection)
        Dim GetID As String

        While reader.Read()
            GetID = reader("Identifier").ToString
            Return GetID
        End While

        xcitoDBConnection.Close()

        ' Catch ex As ApplicationException
        '  ex.Source = ("Selection Error")
        ' Throw ex

        ' Finally

        'End Try
    End Function
End Class

【问题讨论】:

  • 知道sql注入但你还是犯了罪。双重考虑berated
  • 我不在乎你是否批评或批评我的帖子,因为我在这里发帖不够关心我问过的大多数问题,我都能在这里找到......我已经进行了编辑并按照您的要求删除了代码。感谢您的帮助。
  • 用 IF 替换 While 并移动 Return 到函数末尾。
  • 您是否已单步执行您的代码以验证它是否处于无限循环中?也许您的 SQL 只需要很长时间?
  • 每当您键入 error 一词时,您的下一个任务就是... 发布实际错误

标签: sql vb.net infinite-loop


【解决方案1】:

reader = command.ExecuteReader()

而不是

reader = command.ExecuteReader(CommandBehavior.CloseConnection)

因为您在返回前关闭了连接。 并返回函数结束

关注这个

Public Sub CreateCommand(ByVal queryString As String, _
  ByVal connectionString As String)
  Dim GetID As String

    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As New SqlCommand(queryString, connection)
        Dim reader As SqlDataReader = command.ExecuteReader()
        While reader.Read()
            GetID = reader(0).ToString
        End While 
    End Using
    Return GetID 
End Sub

【讨论】:

  • 优秀!!!非常感谢!!看起来我的回归并没有结束。我在这里发布后注意到“返回获取 ID”导致函数退出并且它不会执行超出“返回获取 ID”的任何内容,包括退出循环。这很有意义。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 2015-12-08
  • 1970-01-01
  • 2023-03-22
  • 2016-04-08
  • 2010-11-01
  • 2021-12-31
相关资源
最近更新 更多