mysql
  • vb.net
  • 2017-04-05 205 views 0 likes 
    0

    我有這個函數從數據庫返回學生的具體信息。 這是代碼。函數從數據庫返回數組

    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」))

    結果:

    但是,我想返回從查詢學生的信息的數組。

    當我把它叫做是這樣的功能:

    MSGBOX(arrInfo( 「STUD0027」)( 「姓氏」))

    我想這一個,但不工作。

    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 
    

    我該如何實現這個數組返回?

    非常感謝任何幫助。

    感謝

    +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對象。

    +0

    好的,我會嘗試這一個..謝謝 – user3451123

    相關問題