2013-01-12 2 views
0

Access 데이터베이스에서 문자열 값을 선택한 다음 배열에 루프 문을 수행 할 수 있도록 문자열 배열에 저장하려고합니다.배열에 데이터베이스 쿼리 결과를 추가하는 방법

그러나 쿼리 결과를 배열에 배치하는 방법을 모르겠습니다. 데이터베이스를 쿼리하는 방법을 알고 있지만 필요한 것은 배열에 결과를 저장하는 것입니다.

내 선택 진술 문은 Select motonum from moto입니다. motonum을 배열에 넣고 싶습니다. 데이터를 읽을 수

전체 코드는 다음과 같습니다

이 있습니다
connect2() 
If Not cnn2.State = ConnectionState.Open Then 
    'open connection 
    cnn2.Open() 
    'MessageBox.Show("chk2") 
End If 
cmd5.Connection = cnn2 
cmd5.CommandText = "Select motonum from moto" 
myData5 = cmd5.ExecuteReader 
While myData5.Read 
    'code to return results here 
End While` 

답변

7

다른 방법의 수는 프로젝트의 실제 요구에 따라이 접근 할 수 있습니다. 무엇보다 먼저 반환 유형으로 문자열 배열이 필요한지 물어볼 것입니다. 대부분의 경우 배열은 IEnumerable을 구현하는 List (Of String) 또는 다른 형식보다 덜 유용합니다.

여기에는 List (Of String)이 관련된 두 가지 옵션이 있습니다. 그러나 한 다음 데이터로 작업의 목록 유형의 많은 유용한 방법을 사용하도록 선택할 수 있습니다 호출자에 대한 목록을 반환

이 방법입니다 내가 추천 할 것 : 여기

Public Function getListOfMotonum() As List(Of String) 
    Dim SQL As String = "SELECT motonum FROM moto" 

    Dim output As New List(Of String)() 

    ' Set the connection string in the Solutions Explorer/Properties/Settings object (double-click) 
    Using cn = New SqlConnection(Properties.Settings.[Default].MyConnectionString) 
     Using cmd = New SqlCommand(SQL, cn) 
      cn.Open() 

      Try 
       Dim dr = cmd.ExecuteReader() 
       While dr.Read() 
        output.Add(dr("motonum").ToString()) 
       End While 
      Catch e As SqlException 
       ' Do some logging or something. 
       MessageBox.Show("There was an error accessing your data. DETAIL: " & e.ToString()) 
      End Try 
     End Using 
    End Using 

    Return output 

End Function 

프로젝트가 문자열 배열을 필요로

Private Sub PrintListToConsole() 
    Dim MyMotonumList = Me.getListOfMotonum() 

    For Each item As String In MyMotonumList 
     Console.WriteLine(item) 
    Next 
End Sub 

경우, 접근 방식은 다를 수 :이 기능의 출력을 소비 코드의 사소한 예입니다.

Private Sub PrintArrayToConsole() 
    Dim MyMotonumArray = Me.getArrayOfMotonum() 

    For Each item As String In MyMotonumArray 
     Console.WriteLine(item) 
    Next 
End Sub 
: 목록을 반환 원래의 기능을 소모, 당신은 당신의 클라이언트 코드에서 같은 방법을 사용할 수 있습니다,

' Change the return type in the function signature: 
Public Function getArrayOfMotonum() As String() 
    Dim SQL As String = "SELECT motonum FROM moto" 
    Dim output As New List(Of String)() 

    ' . . . Same Data Access code as above: 

    ' Just use the .ToArray method of the List class HERE: 
    Return output.ToArray() 

End Function 

을 또는 : 당신은 몇 약간의 수정과 같은 함수에서 문자열을 반환 할 수 있습니다

함수에서 List를 반환하면 많은 유용한 메서드가있는보다 유연한 반환 형식이 제공됩니다.

부수적으로 데이터 액세스 리소스를 사용할 때 Using 블록을 사용하도록 권장합니다. 이렇게하면 Connection 객체와 Command 객체를 올바르게 분리하고 처리 할 수 ​​있습니다.

관련 문제