user3451123
user3451123

Reputation: 3

Function Return array from Database

I have this function that return specific info of student from database. Here's the code.

Public Function arrInfo(Byval id as String)
    Dim name as String = ""
    DBCon_Open()
    Dim Cmd = New MySqlCommand("SELECT * FROM student WHERE student_id ='" & id & "'", con)
    Cmd.CommandTimeout = 0
    Dim rs = Cmd.ExecuteReader

    Do While rs.Read
        name = rs.Item("firstname")
    Loop
    rs.Close()
    Cmd.Dispose()
    DBCon_Close()

    Return name

End Function

MsgBox(arrInfo("STUD0027"))

Result: Ben

But, I want to return an array of info of a student from the query.

When I call the function it goes something like this:

MsgBox(arrInfo("STUD0027").("lastname"))

I tried this one but not working.

Public Function arrInfo(Byval id as String)

    DBCon_Open()
    Dim Cmd = New MySqlCommand("SELECT * FROM student WHERE student_id ='" & id & "'", con)
    Cmd.CommandTimeout = 0
    Dim rs = Cmd.ExecuteReader
    rs.Close()
    Cmd.Dispose()
    DBCon_Close()

    Return rs.Read

End Function

How can I achieve this array return?

Any help very much appreciated.

Thanks

Upvotes: 0

Views: 152

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 416039

Try this:

Public Iterator Function arrInfo(Byval id as String) As IEnumerable(Of IDataRecord)
    'In most cases, the best practice in .Net is to use a new connection object each time, to take advantage of connection pooling
    Using cn  As New MySqlConnection(DBCon.ConnectionString), _
          cmd As New MySqlCommand("SELECT * FROM student WHERE student_id = @id", cn)

        cmd.Parameters.Add("@id", MySqlDbType.VarChar, 8).Value = id
        cn.Open()

        Using rdr = cmd.ExecuteReader()
           While rdr.Read()
              Yield Return rdr
           End While
           rdr.Close()
        End Using 
    End Using 'Using block will close and dispose your connection, **even if an exception is thrown**. The existing code would have left it hanging open. 
End Function

It's not exactly an array, but it has some similar properties. You can use it like this:

For Each record As IDataRecord In arrInfo("STUD0027")
    MsgBox(String.Format("Name: {0} {1}", record("firstname"), record("lastname")))
Next record

You should also look into the DataTable and DataSet objects.

Upvotes: 1

Related Questions