Search code examples
mysql.netdatabasevb.netresponse

MySQL Select Response Size .NET


Is it possible to receive the size of a MySQL response before reading it? To be able to have a progressbar giving status about the receiving process.

Public Function QUERY(ByVal queryString As String, ByVal connection As MySqlConnection)
Try
    Dim newQuery As String() = Split(queryString, ":")
    For Each Query In newQuery
        Dim cmd As New MySqlCommand(Query, connection)
        Dim reader As MySqlDataReader
        reader = cmd.ExecuteReader()
        While reader.Read()
        End While
        reader.Close()
    Next
Catch ex As Exception
    console("Error: " & ex.Message)
    Return ex.Message
End Try
Return ""
End Function

Solution

  • No, using a DataReader you cannot know the number of records returned by your query until you reach the end of the reader. However you could use multiple statements in your query where the first statement is a count of your data.

    This is a possible example:

    using con = new MySqlConnection("your_connection_string")
        con.Open()
        Dim cmd As MySqlCommand = new SqlCommand("SELECT COUNT(*) FROM MyTable;" & _
                                                 "SELECT * FROM MyTable", con)
        Dim dr as MySqlDataReader = cmd.ExecuteReader()
        if dr.HasRows Then        
            dr.Read()
            Dim count = Convert.ToInt32(dr(0))
            Console.WriteLine("Reading:" & count.ToString() & " records")
            dr.NextResult()
            while dr.Read()
                Console.WriteLine("Record:" + dr(dr.GetOrdinal("TableID")).ToString())
            End While
        End if
    End Using