0

Is there a way to store data from a sql data reader values to an array?

this is my code

 Dim machines() As Integer
Sub machine_entire()
    Try
        'getting lines from the database
        If conn.State = ConnectionState.Closed Then conn.Open()
        With cmd
            .Connection = conn
            .CommandText = "select machineID from tbl_prod_machine where lineID = '" & lineID & "' order by machineID asc"
        End With
        dr = cmd.ExecuteReader
        If dr.HasRows Then
            While dr.Read
                machines = {dr.GetInt32(dr.GetOrdinal("machineID"))}
            End While
            dr.Close()
        End If
        dr.Close()
    Catch ex As DataException
        MessageBox.Show(ex.Message, ex.GetType.ToString)
    Catch ex As SqlException
        MessageBox.Show("Sql Server Error # " & ex.Number & ": " & ex.GetType.ToString)
    End Try
End Sub

thank you! for the help

3
  • 1
    If you used a DataTable, you could just use the values from that handy container. Or you could use a List(of Integer) and fill it without having to know how many things there are ahead of time. An array is a bad choice for this: the DR cant tell you how many rows there are, so you cant know how big to make the array. Commented Jul 15, 2014 at 0:52
  • Yes, it's possible. Use FieldCount and Item(Int32). msdn.microsoft.com/en-us/library/…. This gets you an array of column values, which is probably not what you want, according to above code. What do you expect as a result of this command? machines = {dr.GetInt32(dr.GetOrdinal("machineID"))} Commented Jul 15, 2014 at 0:56
  • stackoverflow.com/questions/1370543/… Its C# code but might be useful Commented Jul 15, 2014 at 1:55

1 Answer 1

0

If it's just a list of integer, I would use a List(Of )

Dim machines As New List(Of Integer)

After than you just add the values to the list

machines.Add(dr.GetInt32(dr.GetOrdinal("machineID")))

Side note, I would rename your function and make it return the list. In this context, lineId and machines do not seem a good idea to be outside of the function.

Function GetMachineIdsFromLine(ByVal lineId) As List(Of Integer)

Also, it is recomended to open connection only when needed and close them as soon as possible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.