0

我的代码从 SQL 数据库中检索结果时遇到了一个奇怪的问题。代码如下,但基本如下:

打开连接,然后立即执行查询。8/10 倍这没有问题,但有时莫名其妙地执行 get 的查询不会返回任何结果,即使它是对未修改的同一数据库的完全相同的查询。我注意到,如果我在打开连接和关闭连接之间放入一个 threading.sleep 函数,这个问题就会完全消失,但由于显而易见的原因,这并不理想。

我尝试查询连接的状态以查看它是否已准备好,但它总是报告它已打开,即使它没有从数据库中获得任何结果。

有没有人有任何想法?

    'Runs the passed query and returns each row as an object within an ArrayList
    Function Get_Results(ByVal query As String, ByVal ConnectionStringName As String) As ArrayList
        Dim sqlComm As SqlCommand = Get_Connection(query, ConnectionStringName)

        'Open that connection
        sqlComm.Connection.Open()

        'This part doesn't work because the connection will always report that it's open.
        While sqlComm.Connection.State <> Data.ConnectionState.Open
            Threading.Thread.Sleep(100)
        End While

        'pause and wait for the connection to fully open (maybe?)
        'Threading.Thread.Sleep(100)

        'Execute the query and store all of the results into the SqlDataReader.
        Dim sqlRead As SqlDataReader = sqlComm.ExecuteReader()

        Dim result As ArrayList = New ArrayList

        'Read each row one by one.
        While sqlRead.Read()
            'Create an object of the size needed.
            Dim row(sqlRead.FieldCount - 1) As Object

            'Fill the row object with the values.
            sqlRead.GetValues(row)

            'Add the result object to the array.
            result.Add(row)
        End While

        'Close all open connections to the database.
        sqlRead.Close()
        sqlComm.Connection.Close()

        Return result
    End Function
4

0 回答 0