Search code examples
mysqlvb.netmysqldatareader

MySqlDataReader not returning data


As part of a project to import data into wordpress via screen scraping I've a database table of old and new URL's stored in a MySQL database. In the example below the ExecuteReader command doesn't appear to be returning any data (-1 rows effected), I've ran the SQL via workbench and that returns data, so it's not the SQL or data in the database.

At other times within the code I've called ExecuteNonQuery() and ExecuteScalar() both without issue (so it isn't the connection string).

Any ideas what to try next?

    Dim SQL As String
    Dim conn As MySqlConnection = New MySqlConnection(_CONNECTIONSTRING)

    SQL = "SELECT OrgURL, NewURL FROM `wp_user`.`tbl_linkdata`"

    Try
        conn.Open()
        Dim cmd As MySqlCommand = New MySqlCommand(SQL, conn)
        Dim dr As MySqlDataReader = cmd.ExecuteReader()
        While (dr.Read)
            LinkHashMap.Add(dr.GetString(0), dr.GetString(1))
        End While
        Console.ForegroundColor = ConsoleColor.Cyan
        Console.WriteLine("The Hash map contains " + dr.RecordsAffected + " rows")
        dr.Close()

    Catch ex As Exception
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine("Exception loading the hashtable : " + ex.Message)
    Finally
        conn.Dispose()
    End Try

Solution

  • DataReader.RecordsAffected always returns -1 for a SELECT command. What does LinkHashMap.Count return? In MySqlDataReader it is the same:

    "The number of rows changed, inserted, or deleted. -1 for SELECT statements"

    If you want to count the number of records you can use LinkHashMap.Count.

    You: "LinkHashMap is "Nothing" "

    How do you want to add something to it without initializing it first? A NullReferenceException should have happened. So initialize the dictionary (or whatever it is) first via constructor:

    Dim LinkHashMap As New Dictionary(Of String, String)
    While (dr.Read)
        LinkHashMap.Add(dr.GetString(0), dr.GetString(1))
    End While