The following code pulls data from a MySql connection and returns the array (output). This two dimensional array only works when the number of rows and columns are specified before running the query.
Is there a way to get around this? A non-fixed array size? Please help!
Public Function GetUsers() As String(,)
Dim GetCommand As MySqlCommand
Dim SQL As String = "Select * From users"
Dim output(,) As String
Dim intRowCount As Integer = 2
Dim intColumnCount As Integer = 3 ' Users Count
ReDim output(intColumnCount - 1, intRowCount - 1)
Dim GetMyConn As New MySqlConnection
GetMyConn.ConnectionString = "server = mysql.com;user id=rtest;password=test1234;database=rtestdb;"
GetMyConn.Open()
GetCommand = New MySqlCommand(SQL, GetMyConn)
Dim counter As Integer = 0
Try
Dim getResult As Object = GetCommand.ExecuteReader()
While getResult.Read()
output(counter, 0) = getResult("username").ToString()
output(counter, 1) = getResult("game_ip").ToString()
counter = counter + 1
End While
Catch e As MySqlException
MessageBox.Show("There was an error accessing your data. DETAIL: " & e.ToString())
End Try
GetMyConn.Close()
Return output
End Function
'''
Advertisement
Answer
Use this instead
output(counter, 0) = getResult.GetString(0)
output(counter, 1) = getResult.GetString(1)
When you have integer use
reader.GetInt32(0)
and so on
To get the correct dimensions for your array
Change your select statement like below
Dim SQL As String = "Select (SElECT Count(*) rowcount FROM users),* From users"
So you have in your result table a column more with the row count in every row.
Now to redim your array. the Columncount you should know. Else you have to add also
,(SELECT count(*) FROM information_schema.columns
WHERE table_name ='users') columncount
So and then you have to adept your datareader
Try
Dim getResult As Object = GetCommand.ExecuteReader()
If getResult.Read() Then
ReDim output(intColumnCount - 1, Integer.Parse(getResult("rowcount ")) - 1)
output(0, 0) = getResult("username").ToString()
output(0, 1) = getResult("game_ip").ToString(
counter += 1
While getResult.Read()
output(counter, 0) = getResult("username").ToString()
output(counter, 1) = getResult("game_ip").ToString()
counter = counter + 1
End While
END IF
Catch e As MySqlException
MessageBox.Show("There was an error accessing your data. DETAIL: " & e.ToString())
End Try
The idea is to get the first row, catch rowcount and redimension the array properly with the right diemnsions. As described you can if you want do the same with with thecoumnsnumber, if you want to be even more flexible.