如何将sql查询值存储到数组中

时间:2012-07-25 15:06:45

标签: vb.net

Dim sql As String = "Select ProductID From OrderDetail Order By ProductID Desc"
    Dim command As New SqlCommand(sql, connection)
    Dim reader1 As SqlDataReader = command.ExecuteReader()

如何将我检索到的所有产品存储到数组中?

2 个答案:

答案 0 :(得分:2)

Dim list As New List(Of Integer)

Using reader As SqlDataReader = command .ExecuteReader()
    While reader.Read()
        list.Add(reader.GetInt32(reader.GetOrdinal("ProductID")))
    End While
End Using
'check  list.ToArray() now

编辑:但是,我将返回一个通用列表的整数(如果你只想返回ProductId)或一个列表{ {1}}对象

ProductClass

编辑2 根据评论, 要检索标签文本中的放置,您可以执行此操作

Private Function GetProductIDs() As IList(Of Integer)

    Dim list As New List(Of Integer)
    Dim conStr = "write your connection string here"

    Using connection As New SqlConnection(conStr )
        Dim sql As String = "Select ProductID From OrderDetail Order By ProductID Desc"
        Dim command As New SqlCommand(sql, connection)
        Using reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
                list.Add(reader.GetInt32(reader.GetOrdinal("ProductID")))
            End While
        End Using
    End Using

    Return list

End Function

假设Dim str As String str = String.Join(",", GetProductIDs()) Label1.Text=str; 是标签控件的I.D Label1方法将返回一个由逗号分隔的ProductId字符串,如String.Join

答案 1 :(得分:0)

SQLdr = SQLCmd.ExecuteReader 'Gets Data

While dr.Read() 'While Data is Present        
      MsgBox(dr("Column Name")) 'Show data in a Message Box
End While

Loop While SQLdr.NextResult() 'Move to the Next Record

http://www.daniweb.com/software-development/vbnet/code/216920/sql-in-vb.net