函数从数据库返回数组

时间:2017-04-05 04:02:06

标签: mysql vb.net

我有这个函数从数据库返回学生的特定信息。 这是代码。

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&#34))

结果: Ben

但是,我想从查询中返回一个学生信息数组。

当我调用该函数时,它会像这样:

MSGBOX(arrInfo(" STUD0027")("姓&#34))

我尝试了这个,但没有工作。

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

如何实现此数组返回?

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:1)

试试这个:

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

它不完全是一个数组,但它有一些类似的属性。您可以像这样使用它:

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

您还应该查看DataTableDataSet个对象。