Recordset 열기
Open method
커서를 엽니다.
다음 코드는 Biblio.mdb에 연결하고, Titles 테이블에서 모든 레코드를 선택하여 직접 실행 창에 첫 번째 필드의 값을 출력하는 작업을 수행합니다.
Sub ADOExample()
' Declare the variables
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
' Define the connection string and open the connection
conn.connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
conn.Open
' Define the SQL query and open the recordset
Dim strSQL As String
strSQL = "SELECT * FROM Titles"
With rs
.Open strSQL, conn, 1, 3 ' 1 = adOpenKeyset, 3 = adLockOptimistic
If Not .EOF Then
Do While Not .EOF
Debug.Print .Fields(0).Value ' Print the value of first field in Immediate Window.
.MoveNext ' Move to next record.
Loop
End If
.Close ' Close the recordset.
End With
conn.Close ' Close the connection.
Set rs = Nothing ' Clean up.
Set conn = Nothing
End Sub
Recordset 상태 확인하기
State property
해당 개체의 상태가 열려 있는지 또는 닫혀 있는지 모든 관련 개체에 대해 나타냅니다. 만약 해당 개체가 비동기 메서드를 실행 중이라면, 현재 해당 개체의 상태가 연결 중인지, 실행 중인지 또는 검색 중인지를 나타냅니다.
다음 코드는 Northwind.accdb에 연결하고, Customers 테이블에서 모든 레코드를 선택한 후, Recordset 개체의 상태를 확인하여 직접 실행 창에 해당 상태를 출력하는 작업을 수행합니다.
Sub CheckRecordsetState()
Dim con As ADODB.Connection
Dim rst As ADODB.Recordset
Set con = New ADODB.Connection
Set rst = New ADODB.Recordset
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Northwind.accdb;"
' Open a RecordSet
rst.Open "SELECT * FROM Customers", con
' Check the state of the RecordSet and print appropriate message.
If (rst.State And adStateClosed) = adStateClosed Then
Debug.Print "The recordset is closed."
End If
If (rst.State And adStateOpen) = adStateOpen Then
Debug.Print "The recordset is open."
End If
If (rst.State And adStateConnecting) = adStateConnecting Then
Debug.Print "The connection object is connecting."
End If
If (rst.State And adStateExecuting) = adStateExecuting Then
Debug.Print "The command object is executing."
End If
If (rst.State And adStateFetching) = adStateFetching Then
Debug.Print "The recordset object is fetching rows."
End If
End Sub
Recordset 내에서 이동하기
MoveFirst method
Recordset의 첫 번째 레코드로 이동합니다.
Sub RetrieveAuthorsFromDatabase()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
On Error GoTo ErrorHandler
' Open the connection.
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' Open the Recordset with CursorType adOpenStatic to allow reverse navigation.
rs.Open "SELECT * FROM Authors", conn, adOpenStatic
' Move to the last record.
rs.MoveLast
' Print the last author's name.
Debug.Print "Last Author: " & rs.Fields("Author").Value
' Move back to the first record.
rs.MoveFirst
' Print the first author's name.
Debug.Print "First Author: " & rs.Fields("Author").Value
ExitProcedure:
' Close the Recordset and Connection objects and release their resources.
If Not rs Is Nothing Then
If rs.State = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
If Not conn Is Nothing Then
If conn.State = adStateOpen Then
conn.Close
End If
Set conn = Nothing
End If
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number
Resume ExitProcedure
End Sub
MoveLast method
Recordset의 마지막 레코드로 이동합니다.
Sub RetrieveAuthorsFromDatabase()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
On Error GoTo ErrorHandler
' Open the connection.
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' Open the Recordset with CursorType adOpenStatic to allow reverse navigation.
rs.Open "SELECT * FROM Authors", conn, adOpenStatic
' Move to the last record.
rs.MoveLast
' Print the last author's name.
Debug.Print "Last Author: " & rs.Fields("Author").Value
ExitProcedure:
' Close the Recordset and Connection objects and release their resources.
If Not rs Is Nothing Then
If rs.State = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
If Not conn Is Nothing Then
If conn.State = adStateOpen Then
conn.Close
End If
Set conn = Nothing
End If
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number
Resume ExitProcedure
End Sub
MoveNext method
Recordset의 현재 위치 다음에 있는 레코드로 이동합니다.
Sub RetrieveAuthorsFromDatabase()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
On Error GoTo ErrorHandler
' Open the connection.
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' Open the Recordset.
rs.Open "SELECT * FROM Authors", conn
' Loop through the Recordset until EOF (End Of File).
Do Until rs.EOF
Debug.Print "Author: " & rs.Fields("Author").Value
rs.MoveNext
Loop
ExitProcedure:
' Close the Recordset and Connection objects and release their resources.
If Not rs Is Nothing Then
If rs.State = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
If Not conn Is Nothing Then
If conn.State = adStateOpen Then
conn.Close
End If
Set conn = Nothing
End If
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number
Resume ExitProcedure
End Sub
MovePrevious method
Recordset의 현재 위치 앞에 있는 레코드로 이동합니다.
Sub RetrieveAuthorsFromDatabaseReverse()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
On Error GoTo ErrorHandler
' Open the connection.
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' Open the Recordset with CursorType adOpenStatic to allow reverse navigation.
rs.Open "SELECT * FROM Authors", conn, adOpenStatic
' Move to the last record.
rs.MoveLast
' Loop through the Recordset from end to start.
Do Until rs.BOF
Debug.Print "Author: " & rs.Fields("Author").Value
rs.MovePrevious
Loop
ExitProcedure:
' Close the Recordset and Connection objects and release their resources.
If Not rs Is Nothing Then
If rs.State = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
If Not conn Is Nothing Then
If conn.State = adStateOpen Then
conn.Close
End If
Set conn = Nothing
End If
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number
Resume ExitProcedure
End Sub
Move method
현재 레코드의 위치를 이동합니다.
인수가 0보다 크면 현재 레코드 위치가 정방향으로(Recordset의 끝 부분으로) 이동되고 NumRecords가 0보다 작으면 역방향으로(Recordset의 시작 부분으로) 이동됩니다.
다음 코드는 Move 메서드를 사용하여 세 번째 레코드로 이동합니다. 그런 다음 현재 위치의 작가 이름을 출력합니다.
Sub MoveExample()
Dim rst As Object
' Create the ADODB objects and open the database.
Set rst = CreateObject("ADODB.Recordset")
' Define the constants.
Const adOpenKeyset = 1
rst.Open "Authors", _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;", _
adOpenKeyset
' Move to the third record.
rst.Move 3
If Not rst.EOF Then
Debug.Print "Current author is: " & rst.Fields("Author").Value
Else
Debug.Print "Moved past end of file."
End If
' Close and release Recordset object from memory.
If Not (rst Is Nothing) Then
If (rst.State And &H1) <> 0 Then ' Check if it's open.
rst.Close
End If
Set rst = Nothing
End If
End Sub
Recordset 개체의 현재 레코드가 있는 위치 나타내기
AbsolutePosition property
Sub RetrieveAuthorsFromDatabase()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
On Error GoTo ErrorHandler
' Open the connection.
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' Open the Recordset with CursorType adOpenStatic to allow reverse navigation.
rs.Open "SELECT * FROM Authors", conn, adOpenStatic
' Move to the last record.
rs.MoveLast
' Print the last author's name and its position.
Debug.Print "Last Author: " & rs.Fields("Author").Value & ", Position: " & rs.AbsolutePosition
ExitProcedure:
' Close the Recordset and Connection objects and release their resources.
If Not rs Is Nothing Then
If rs.State = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
If Not conn Is Nothing Then
If conn.State = adStateOpen Then
conn.Close
End If
Set conn = Nothing
End If
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number
Resume ExitProcedure
End Sub
특정 레코드의 위치를 저장하고 검색하기
Bookmark property
다음 코드는 첫 번째 레코드의 위치를 bookmarkFirst 변수에 저장하고, 마지막으로 이동한 후 첫 번째 레코드로 다시 돌아갑니다
Sub RetrieveAuthorsFromDatabase()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
On Error GoTo ErrorHandler
' Open the connection.
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' Open the Recordset with CursorType adOpenStatic to allow reverse navigation.
rs.Open "SELECT * FROM Authors", conn, adOpenStatic
' Save the position of the first record.
Dim bookmarkFirst As Variant
bookmarkFirst = rs.Bookmark
' Move to the last record.
rs.MoveLast
' Print the last author's name.
Debug.Print "Last Author: " & rs.Fields("Author").Value
' Return to the first record using Bookmark property.
rs.Bookmark = bookmarkFirst
' Print the first author's name again.
Debug.Print "First Author: " & rs.Fields("Author").Value
ExitProcedure:
' Close the Recordset and Connection objects and release their resources.
If Not rs Is Nothing Then
If rs.State = adStateOpen Then
rs.Close
End If
Set rs = Nothing
End If
If Not conn Is Nothing Then
If conn.State = adStateOpen Then
conn.Close
End If
Set conn = Nothing
End If
Exit Sub
ErrorHandler:
MsgBox Err.Description, vbCritical, "Error: " & Err.Number
Resume ExitProcedure
End Sub
다음 코드는 북마크의 위치를 비교합니다.
Sub CompareAuthorPositions()
Dim vFirstBookmark As Variant
Dim vSecondBookmark As Variant
Dim lCompareResult As Long
Dim rst As Object
' Create the ADODB objects and open the database.
Set rst = CreateObject("ADODB.Recordset")
' Define the constants.
Const adOpenKeyset = 1
Const adCompareLessThan = -1
rst.Open "Authors", _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;", _
adOpenKeyset
rst.MoveFirst
rst.Find "Author='Jason'"
If Not rst.EOF Then ' Check if record found.
vFirstBookmark = rst.Bookmark
Else
Debug.Print "Author Jason not found."
Exit Sub ' Exit the subroutine if author not found.
End If
rst.MoveFirst
rst.Find "Author='Tammi'"
If Not rst.EOF Then ' Check if record found.
vSecondBookmark = rst.Bookmark
Else
Debug.Print "Author Tammi not found."
Exit Sub ' Exit the subroutine if author not found.
End If
lCompareResult = rst.CompareBookmarks(vFirstBookmark, _
vSecondBookmark)
Select Case lCompareResult
Case Is = adCompareLessThan:
Debug.Print "Jason comes before Tammi"
Case Is > 0:
Debug.Print "Tammi comes before Jason"
Case Else:
Debug.Print "Jason and Tammi are at the same position"
End Select
' Close and release Recordset object from memory.
If Not (rst Is Nothing) Then
If (rst.State And &H1) <> 0 Then ' Check if it's open.
rst.Close
End If
Set rst = Nothing
End If
End Sub
Paging
PageCount property
Recordset 개체에 포함된 데이터의 페이지 수를 나타냅니다.
PageSize property
Recordset의 한 페이지를 구성하는 레코드 수를 나타냅니다.기본값은 10입니다.
다음 코드는 PageCount 속성과 PageSize 속성을 사용하는 방법을 보여줍니다.
Sub PagingExample()
Dim rst As Object
' Create the ADODB objects and open the database.
Set rst = CreateObject("ADODB.Recordset")
' Define the constants.
Const adOpenStatic = 3
rst.Open "Authors", _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;", _
adOpenStatic
' Set page size.
rst.PageSize = 25
Debug.Print "Pages: " & CStr(rst.PageCount)
Debug.Print "Page Size: " & CStr(rst.PageSize)
' Close and release Recordset object from memory.
If Not (rst Is Nothing) Then
If (rst.State And &H1) <> 0 Then ' Check if it's open.
rst.Close
End If
Set rst = Nothing
End If
End Sub
' 출력 결과
' Pages: 250
' Page Size: 25
AbsolutePage property
현재 레코드가 있는 페이지를 나타냅니다.
다음 코드는 'Authors' 테이블의 모든 페이지를 순회하며, 각 페이지의 첫 번째 작가 이름을 출력하는 작업을 수행합니다.
Sub PagingExample()
Dim lPageNumber As Long
Dim rst As Object
' Create the ADODB objects and open the database.
Set rst = CreateObject("ADODB.Recordset")
rst.Open "Authors", _
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;", _
adOpenStatic
For lPageNumber = 1 To rst.PageCount
rst.AbsolutePage = lPageNumber
Debug.Print "The first author on page " & _
CStr(lPageNumber) & " is " & _
rst.Fields("Author").Value
Next lPageNumber
' Close and release Recordset object from memory.
If Not (rst Is Nothing) Then
If (rst.State And &H1) <> 0 Then ' Check if it's open.
rst.Close
End If
Set rst = Nothing
End If
End Sub
새 레코드 추가
Recordset.AddNew method
업데이트할 수 있는 Recordset 개체에 대한 새 레코드를 만듭니다.
다음 코드는 하나의 레코드를 추가합니다.
Sub AddNewRecord()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
' 데이터베이스 연결 열기
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' 쿼리 실행 및 Recordset 열기
rs.Open "SELECT * FROM Authors", conn, 2, 3 ' 2: adOpenDynamic, 3: adLockOptimistic
' 새 레코드 추가
rs.AddNew
' 필드 값 설정
rs.Fields("Author").Value = "Steven"
rs.Fields("Year Born").Value = "1974"
rs.Update
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub
다음 코드는 시트에 입력된 값을 읽어와서 추가합니다.
Sub AddNewRecords()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
' 데이터베이스 연결 열기 (예: Access)
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' 쿼리 실행 및 Recordset 열기
rs.Open "SELECT * FROM Authors", conn, 2, 3 ' 2: adOpenDynamic, 3: adLockOptimistic
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1") ' 여기서 "Sheet1"은 실제 작업할 시트 이름으로 변경해야 합니다.
Dim data As Variant
data = ws.Range("A1:B100").Value ' A1:B100 범위의 값을 배열로 읽어옵니다.
Dim i As Long
For i = LBound(data, 1) To UBound(data, 1) ' 배열에 대해 순회합니다.
If Not IsEmpty(data(i, 1)) Then ' 첫 번째 열에 값이 있는 경우만 처리합니다.
' 새 레코드 추가
rs.AddNew
' 필드 값 설정
rs.Fields("Author").Value = data(i, 1) ' 첫 번째 열 값 사용.
rs.Fields("Year Born").Value = data(i, 2) ' 두 번째 열 값 사용.
rs.Update ' 레코드 업데이트.
End If
Next i
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub
특정 종류의 기능을 지원하는지 확인하기
Supports method
지정된 Recordset 개체가 특정 종류의 기능을 지원하는지 여부를 확인합니다.
Syntax
boolean = recordset.Supports (CursorOptions)
반환 값
공급자가 CursorOptions 인수에서 식별하는 모든 기능을 지원하는지 여부를 나타내는 Boolean 값을 반환합니다.
Parameters
CursorOptions : 하나 이상의 CursorOptionEnum 값으로 구성되는 Long 식입니다.
CursorOptionEnum (Access desktop database reference)
Office developer client VBA reference documentation
learn.microsoft.com
다음 코드는 Bookmark 속성을 사용할 수 있는지 확인합니다.
Sub CheckBookmarkSupport()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
' Open the connection.
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\download\Biblio.mdb;"
' Open the Recordset with a forward-only cursor.
rs.CursorType = adOpenForwardOnly
rs.Open "SELECT * FROM Authors", conn
' Check if bookmarks are supported.
If rs.Supports(adBookmark) Then
Debug.Print "Bookmarks are supported."
Else
Debug.Print "Bookmarks are not supported."
End If
' Close the Recordset and Connection.
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub
' 출력 결과
' Bookmarks are not supported.
편집 상태 확인하기
EditMode property
현재 레코드의 편집 상태를 나타냅니다.
반환 값
EditModeEnum 값을 반환합니다.
EditModeEnum - ActiveX Data Objects (ADO)
EditModeEnum
learn.microsoft.com
다음 코드는 EditMode 속성을 이용해서 현재 편집 상태를 출력하는 간단한 예제입니다.
Sub TestEditMode()
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
' 데이터베이스 연결 열기
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
' Recordset 개체 생성 및 SQL 쿼리 실행
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM Authors", conn, 1, 3
' 첫 번째 레코드로 이동
rs.MoveFirst
' 편집 상태 확인
CheckEditMode rs
' 레코드 수정 시작
rs.Fields("Author").Value = "Steven"
' 편집 상태 확인
CheckEditMode rs
' 변경사항 저장
rs.Update
' 편집 상태 확인
CheckEditMode rs
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub
Sub CheckEditMode(rs As Object)
Select Case rs.EditMode
Case 0:
Debug.Print "No edit in progress."
Case 1:
Debug.Print "Edit in progress."
Case 2:
Debug.Print "New record being added."
Case Else:
Debug.Print "Unknown edit mode."
End Select
End Sub
레코드 삭제
Delete method
다음 코드는 Authors 테이블의 Year Born 필드에서 조건이 일치하는 레코드를 삭제합니다.
Sub DeleteRecord()
Dim dbPath As String
Dim tableName As String
dbPath = "D:\download\Biblio.mdb"
tableName = "Authors"
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
' 데이터베이스 연결 열기
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
' Recordset 개체 생성 및 SQL 쿼리 실행
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM " & tableName, conn, 2, 3
' 첫 번째 레코드로 이동
rs.MoveFirst
' 레코드를 순환하면서 조건이 일치하면 삭제합니다.
Do Until rs.EOF
If rs.Fields("Year Born").Value = 2012 Then
rs.Delete adAffectCurrent
Debug.Print "Record deleted."
End If
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
End Sub
데이터 추출하기
GetRows method
Recordset 개체의 여러 레코드를 배열로 검색합니다.
Syntax
array = recordset.GetRows(Rows, Start, Fields )
반환 값
값이 2차원 배열인 Variant를 반환합니다.
Parameters
Rows : (선택 사항) 검색할 레코드 수를 나타내는 GetRowsOptionEnum 값입니다. 기본값은 adGetRowsRest입니다.
GetRowsOptionEnum - ActiveX Data Objects (ADO)
GetRowsOptionEnum
learn.microsoft.com
Start : (선택 사항) GetRows 작업을 시작해야 하는 레코드의 책갈피로 계산되는 String 값 또는 Variant입니다. BookmarkEnum 값을 사용할 수도 있습니다.
BookmarkEnum - ActiveX Data Objects (ADO)
BookmarkEnum
learn.microsoft.com
Fields : (선택 사항) 단일 필드 이름 또는 서수 위치 또는 필드 이름 또는 서수 위치 번호 배열을 나타내는 Variant입니다. ADO는 이러한 필드의 데이터만 반환합니다.
비고
GetRows 메서드를 사용하여 Recordset의 레코드를 2차원 배열로 복사합니다. 첫 번째 아래 첨자는 필드를 식별하고 두 번째 첨자는 레코드 번호를 식별합니다. GetRows 메서드가 데이터를 반환하면 array 변수가 자동으로 올바른 크기로 차원화됩니다.
Rows 인수에 대한 값을 지정하지 않으면 GetRows 메서드는 Recordset 개체의 모든 레코드를 자동으로 검색합니다. 사용 가능한 것보다 많은 레코드를 요청하는 경우 GetRows는 사용 가능한 레코드 수만 반환합니다.
Recordset 개체가 책갈피를 지원하는 경우 Start 인수에서 해당 레코드의 Bookmark 속성 값을 전달하여 GetRows 메서드가 데이터 검색을 시작할 레코드를 지정할 수 있습니다.
GetRows 호출이 반환하는 필드를 제한하려면 Fields 인수에 단일 필드 이름/숫자 또는 필드 이름/숫자 배열을 전달할 수 있습니다.
GetRows를 호출한 후 읽지 않은 다음 레코드는 현재 레코드가 되거나, 레코드가 더 이상 없으면 EOF 속성이 True로 설정됩니다.
다음 코드는 GetRows 메서드를 이용하여 5개의 행만 출력합니다.
Sub GetDataUsingGetRows()
' 변수 정의
Dim conn As Object
Dim rs As Object
Dim arrData As Variant
Dim strSQL As String
Dim dbPath As String
Dim tableName As String
dbPath = "D:\download\Biblio.mdb"
tableName = "Titles"
' 데이터베이스 연결 설정
Set conn = CreateDatabaseConnection(dbPath)
' SQL 쿼리 실행
Set rs = ExecuteSQLQuery(conn, "SELECT * FROM " & tableName)
' 결과 출력
Call PrintData(rs, 5)
' 개체 정리 및 닫기.
CleanUp rs, conn
End Sub
Function CreateDatabaseConnection(dbPath As String) As Object
' 연결 개체 생성 및 데이터베이스에 연결 열기
Set CreateDatabaseConnection = CreateObject("ADODB.Connection")
CreateDatabaseConnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
End Function
Function ExecuteSQLQuery(conn As Object, strSQL As String) As Object
' 레코드셋 개체 생성 및 SQL 쿼리 실행
Set ExecuteSQLQuery = CreateObject("ADODB.Recordset")
ExecuteSQLQuery.CursorType = adOpenStatic
ExecuteSQLQuery.Open strSQL, conn
End Function
Sub PrintData(rs As Object, numRows As Long)
' 배열을 순회하며 데이터 처리.
Dim arrData As Variant
Dim i As Long
Dim j As Long
If Not rs.EOF Then
arrData = rs.GetRows(numRows)
For i = LBound(arrData, 2) To UBound(arrData, 2)
For j = LBound(arrData) To UBound(arrData)
Debug.Print arrData(j, i)
Next j
Next i
End If
End Sub
Sub CleanUp(rs As Object, conn As Object)
' 개체 정리 및 닫기.
rs.Close: Set rs = Nothing
conn.Close: Set conn = Nothing
End Sub
GetString Method
레코드 집합을 문자열로 반환합니다.
Syntax
Variant = recordset.GetString(StringFormat, NumRows, ColumnDelimiter, RowDelimiter, NullExpr)
반환 값
Recordset을 Variant 값인 문자열로 반환합니다(BSTR)
Parameters
StringFormat : Recordset을 문자열로 변환할 방법을 지정하는 StringFormatEnum 값입니다. RowDelimiter, ColumnDelimiter 및 NullExpr 매개 변수는 adClipString의 StringFormat에서만 사용됩니다.
StringFormatEnum - ActiveX Data Objects (ADO)
StringFormatEnum
learn.microsoft.com
NumRows : 선택 요소로서 Recordset에서 변환할 행 수입니다. NumRows를 지정하지 않거나 Recordset의 전체 행 수보다 큰 값을 지정하면 Recordset의 모든 행이 변환됩니다.
ColumnDelimiter : 선택 요소로서 지정할 경우 열 사이에 사용되는 구분 기호이고 그렇지 않은 경우 Tab 문자입니다.
RowDelimiter : 선택 요소로서 지정할 경우 행 사이에 사용되는 구분 기호이고 그렇지 않은 경우 캐리지 리턴 문자입니다.
NullExpr : 선택적 요소로서 지정할 경우 null 값 대신 사용되는 식이고 그렇지 않은 경우 빈 문자열입니다.
주의
스키마 데이터가 아니라 행 데이터가 문자열에 저장되므로 이 문자열을 사용하여 Recordset을 다시 열 수 없습니다.
다음 코드는 세 개의 행을 문자열로 반환합니다.
Sub GetRecordsetString()
' 필요한 라이브러리 참조 설정: Microsoft ActiveX Data Objects x.x Library
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim connectionString As String
Dim sqlQuery As String
Dim dbPath As String
Dim tableName As String
dbPath = "D:\download\Biblio.mdb"
tableName = "Titles"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
sqlQuery = "SELECT * FROM " & tableName
With conn
.Open connectionString ' 데이터베이스에 연결합니다.
Set rs = .Execute(sqlQuery) ' SQL 쿼리를 실행합니다.
If Not rs.EOF Then
Debug.Print rs.GetString(adClipString, 3) ' 결과를 문자열로 가져옵니다.
Else
Debug.Print "No records found."
End If
rs.Close ' Recordset을 닫습니다.
.Close ' 데이터베이스 연결을 닫습니다.
End With
Set rs = Nothing
Set conn = Nothing
End Sub
'출력 결과
' dBASE III : A Practical Guide 1985 0-0038307-6-4 469 22.5 {}
' The dBASE Programming Language 1986 0-0038326-7-8 469 29.5 005.756520 QA76.9.D3D424 1986 {997011870}
' dBASE III Plus 1987 0-0038337-8-X 469 29.5 {}
'ActiveX Data Objects (ADO)' 카테고리의 다른 글
Field Object (0) | 2023.10.03 |
---|---|
Fields Collection (0) | 2023.10.02 |
Connection Object (0) | 2023.08.31 |