본문 바로가기
ActiveX Data Objects (ADO)

Field Object

2023. 10. 3.

Field Object

일반 데이터 형식의 데이터 열을 나타냅니다.

 

속성

ActualSize property

필드 값의 실제 길이를 나타냅니다.

 

설정 및 반환 값

 

Long 값을 반환합니다. 일부 공급자는 이 속성을 설정하여 BLOB 데이터용 공간을 예약할 수 있으며, 이 경우 기본값은 0입니다.

주의
ActualSize 속성을 사용하여 Field 개체 값의 실제 길이를 반환합니다. 모든 필드의 ActualSize 속성은 읽기 전용입니다. ADO에서 Field 개체 값의 길이를 확인할 수 없으면 ActualSize 속성은 adUnknown을 반환합니다.

 

다음 코드는 ActualSize속성을 사용하는 간단한 예를 보여줍니다.

Sub TestActualSize()
    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim fld As ADODB.Field
    
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset
    
    ' DB 연결 설정
    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"
    
    ' SQL 쿼리 실행
    rs.Open "SELECT * FROM Titles", conn, adOpenStatic, adLockReadOnly
    
    ' 각 필드에 대한 ActualSize 출력
    For Each fld In rs.Fields
        Debug.Print fld.Name & ": " & fld.ActualSize & " bytes"
    Next fld
    
    ' Clean up
     rs.Close
     Set rs = Nothing
     conn.Close
     Set conn = Nothing
End Sub

' 출력 결과
' Title: 58 bytes
' Year Published: 2 bytes
' ISBN: 26 bytes
' PubID: 4 bytes
' Description: 8 bytes
' Notes: 0 bytes
' Subject: 0 bytes
' Comments: 6 bytes

Attributes property

개체에 대한 하나 이상의 특성을 나타냅니다.

설정 및 반환 값
Long 값을 설정하거나 반환합니다.

Connection 개체의 경우 Attributes 속성은 읽기/쓰기가 가능하며, 속성 값은 하나 이상의 XactAttributeEnum 값에 대한 합계가 될 수 있습니다. 기본값은 0입니다.

 

 

XactAttributeEnum - ActiveX Data Objects (ADO)

XactAttributeEnum

learn.microsoft.com

Parameter 개체의 경우 Attributes 속성은 읽기/쓰기가 가능하며, 속성 값은 하나 이상의 ParameterAttributesEnum 값에 대한 합계가 될 수 있습니다. 기본값은 adParamSigned입니다.

 

ParameterAttributesEnum - ActiveX Data Objects (ADO)

ParameterAttributesEnum

learn.microsoft.com

Field 개체의 경우 Attributes 속성은 하나 이상의 FieldAttributeEnum 값에 대한 합계가 될 수 있습니다. 일반적으로 이 속성은 읽기 전용이지만 Record의 Fields 컬렉션에 추가된 새 Field 개체의 경우 Field의 Value 속성을 지정하고 데이터 공급자가 Fields 컬렉션의 Update 메서드를 호출하여 새 Field를 제대로 추가한 후에만 Attributes 속성이 읽기/쓰기가 가능해집니다.

 

 

FieldAttributeEnum - ActiveX Data Objects (ADO)

FieldAttributeEnum

learn.microsoft.com

Property 개체의 경우 Attributes 속성은 읽기 전용이며, 속성 값은 하나 이상의 PropertyAttributesEnum 값에 대한 합계가 될 수 있습니다.

 

 

PropertyAttributesEnum - ActiveX Data Objects (ADO)

PropertyAttributesEnum

learn.microsoft.com

 


주의
Attributes 속성을 사용하여 Connection 개체, Parameter 개체, Field 개체 또는 Property 개체의 특성을 설정하거나 반환합니다.

여러 특성을 설정할 경우 해당 상수의 합계를 구할 수 있습니다. 호환되지 않는 상수를 포함하는 합계로 속성 값을 설정하면 오류가 발생합니다.

원격 데이터 서비스 사용 이 속성은 클라이언트 쪽 Connection 개체에서는 사용할 수 없습니다.

 

다음 코드는 Attrubutes 속성을 사용하는 간단한 예제를 보여줍니다.

Sub TestFieldAttributes()
    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim fld As ADODB.Field

    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    ' DB 연결 설정 (예: Access DB)
    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\download\Biblio.mdb;"

    ' SQL 쿼리 실행
    rs.Open "SELECT * FROM Titles", conn, adOpenStatic, adLockReadOnly

    ' 각 필드에 대한 이름과 Attributes 출력
    For Each fld In rs.Fields
        Debug.Print fld.Name & ": " & GetAttributeDescription(fld.Attributes)
    Next fld

    ' Clean up
    rs.Close
    Set rs = Nothing
    conn.Close
    Set conn = Nothing
End Sub

Function GetAttributeDescription(attr As Long) As String
    If attr And adFldUnspecified Then GetAttributeDescription = GetAttributeDescription & "Unspecified" & ","
    If attr And adFldUpdatable Then GetAttributeDescription = GetAttributeDescription & "Updatable" & ","
    If attr And adFldUnknownUpdatable Then GetAttributeDescription = GetAttributeDescription & "Unknown Updatable" & ","
    If attr And adFldIsRowURL Then GetAttributeDescription = GetAttributeDescription & "Is Row URL" & ","
    If attr And adFldIsDefaultStream Then GetAttributeDescription = GetAttributeDescription & "Is Default Stream" & ","
    If attr And adFldMayDefer Then GetAttributeDescription = GetAttributeDescription & "May Defer" & ","
    If attr And adFldNegativeScale Then GetAttributeDescription = "Negative Scale" & ","
    If attr And adFldKeyColumn Then GetAttributeDescription = GetAttributeDescription & "Key Column" & ","
    If attr And adFldRowID Then GetAttributeDescription = GetAttributeDescription & "Row ID" & ","
    If attr And adFldRowVersion Then GetAttributeDescription = GetAttributeDescription & "Row Version" & ","
    If attr And adFldCacheDeferred Then GetAttributeDescription = GetAttributeDescription & "Cache Deferred" & ","
    If attr And adFldFixed Then GetAttributeDescription = GetAttributeDescription & "Fixed" & ","
    If attr And adFldIsChapter Then GetAttributeDescription = GetAttributeDescription & "Is Chapter" & ","
    If attr And adFldIsCollection Then GetAttributeDescription = GetAttributeDescription & "Is Collection" & ","
    If attr And adFldIsNullable Then GetAttributeDescription = GetAttributeDescription & "Is Nullable"
End Function

' 출력 결과
' Title: Unspecified,Unknown Updatable,May Defer,Is Nullable
' Year Published: Unspecified,Unknown Updatable,May Defer,Fixed,Is Nullable
' ISBN: Unspecified,Unknown Updatable,May Defer,Is Nullable
' PubID: Unspecified,Unknown Updatable,May Defer,Fixed,Is Nullable
' Description: Unspecified,Unknown Updatable,May Defer,Is Nullable
' Notes: Unspecified,Unknown Updatable,May Defer,Is Nullable
' Subject: Unspecified,Unknown Updatable,May Defer,Is Nullable
' Comments: Unspecified,Unknown Updatable,May Defer,Is Nullable

DefinedSize property

Field 개체의 데이터 용량을 나타냅니다.

 

반환 값
정의된 필드 크기를 바이트 수로 나타내는 Long 값을 반환합니다.

주의
DefinedSize 속성을 사용하여 Field 개체의 데이터 용량을 확인합니다.

DefinedSize 속성과 ActualSize 속성은 다릅니다. 예를 들어 선언된 형식이 adVarChar이고 DefinedSize 속성 값이 50인 Field 개체의 경우 ActualSize 속성 값으로 단일 문자의 길이(바이트)를 반환합니다.

 

다음 코드는 DefinedSize 속성을 사용하는 간단한 예제입니다.

Sub TestFieldAttributes()
    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim fld As ADODB.Field
    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

    ' DB 연결 설정
    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    ' SQL 쿼리 실행
    rs.Open "SELECT * FROM " & tableName, conn, adOpenStatic, adLockReadOnly

    ' 각 필드에 대한 이름과 DefinedSize 출력
    For Each fld In rs.Fields
        Debug.Print fld.Name & ": " & fld.DefinedSize
    Next fld

    ' Clean up
    rs.Close
    Set rs = Nothing
    conn.Close
    Set conn = Nothing

End Sub

' 출력 결과
' Title: 255
' Year Published: 2
' ISBN: 20
' PubID: 4
' Description: 50
' Notes: 50
' Subject: 50
' Comments: 536870910

다음 코드는 ActualSize 속성과 DefinedSize 속성의 차이를 보여줍니다.

Sub PrintSupplierInfo()
    On Error GoTo ErrorHandler

    ' 레코드셋 및 연결 변수
    Dim rstStores As ADODB.Recordset
    Dim SQLStores As String
    Dim strCnxn As String

    ' 레코드 변수
    Dim strMessage As String

    ' Stores 테이블에 대한 레코드셋 열기
    strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
              "Initial Catalog='Northwind';Integrated Security='SSPI';"

    Set rstStores = New ADODB.Recordset

    SQLStores = "Suppliers"

    ' 레코드셋 열기
    rstStores.Open SQLStores, strCnxn, adOpenForwardOnly, adLockReadOnly, adCmdTable

    ' 레코드셋을 순환합니다.
    Do Until rstStores.EOF
        strMessage = strMessage & vbCrLf & _
                     "Company name: " & rstStores!CompanyName & vbCrLf & _
                     "Defined size: " & rstStores!CompanyName.DefinedSize & vbCrLf & _
                     "Actual size:  " & rstStores!CompanyName.ActualSize

        rstStores.MoveNext
    Loop

    MsgBox strMessage, vbOKOnly + vbInformation, "ADO ActualSize Property (VBA)"

    ' 정리 작업 수행
    rstStores.Close
    Set rstStores = Nothing
    Exit Sub

ErrorHandler:
    ' 정리 작업 수행
    If Not rstStores Is Nothing Then
        If rstStores.State = adStateOpen Then rstStores.Close
    End If
    Set rstStores = Nothing

    If Err.Number <> 0 Then
        MsgBox Err.Source & "-->" & Err.Description, , "Error"
    End If
End Sub

Name property

개체의 이름을 나타냅니다.

 

설정 및 반환 값
개체의 이름을 나타내는 문자열 값을 설정하거나 반환합니다.

 

비고
Name 속성을 사용하여 Command, Property, Field 또는 Parameter 객체의 이름을 할당하거나 검색합니다.

Command 객체에서는 값이 읽기/쓰기 가능하며 Property 객체에서는 읽기 전용입니다.

Field 객체의 경우, 일반적으로 Name은 읽기 전용입니다. 그러나 Fields 컬렉션에 추가된 새 Field 객체의 경우, Value 속성이 지정되고 Fields 컬렉션의 Update 메서드를 호출하여 새 Field를 성공적으로 추가한 후에만 Name이 읽기/쓰기 가능합니다.

아직 Parameters 컬렉션에 추가되지 않은 Parameter 객체의 경우 Name 속성은 읽기/쓰기 가능합니다. 추가된 Parameter 객체 및 다른 모든 객체의 경우 Name 속성은 읽기 전용입니다. 이름은 컬렉션 내에서 고유할 필요가 없습니다.

객체의 Name 속성을 순서 참조로 가져올 수 있으며, 그 후에는 해당 속성을 직접 이름으로 참조할 수 있습니다. 예를 들어, rstMain.Properties(20).Name이 "Updatability"를 반환하는 경우, 이 속성을 이후에는 "Updatability"로 참조할 수 있습니다.

 

다음 코드는 필드 이름을 출력하는 간단한 예제입니다.

Sub ShowFieldNames(rs As ADODB.Recordset)
    Dim fld As ADODB.Field
    For Each fld In rs.Fields
        Debug.Print fld.Name
    Next fld
End Sub
Sub ADOExample()
' 변수 선언
    Dim conn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
    Dim dbPath As String
    Dim tableName As String

    dbPath = "D:\download\Biblio.mdb"
    tableName = "Authors"

    ' 데이터베이스에 연결
    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    ' SQL 쿼리 실행
    rs.Open "SELECT * FROM " & tableName, conn

    Call ShowFieldNames(rs)

    ' 작업 완료 후 Recordset과 Connection 닫기
    rs.Close
    Set rs = Nothing
    conn.Close
    Set conn = Nothing

End Sub

OriginalValue property

변경 작업을 수행하기 전에 레코드에 있었던 Field의 값을 나타냅니다.

 

반환 값
변경 작업 이전의 필드 값을 나타내는 Variant 값을 반환합니다.

 

비고
OriginalValue 속성을 사용하여 현재 레코드의 필드에 대해 원래 필드 값을 반환합니다.

 

Update 메서드를 호출한 후 공급자가 변경 내용을 기본 데이터 원본에 쓰는 '즉시 업데이트 모드'에서 OriginalValue 속성은 변경 작업 이전, 즉 마지막 Update 메서드 호출 이후의 필드 값을 반환합니다. 이 값은 CancelUpdate 메서드에서 Value 속성을 바꾸는 데 사용하는 값과 같습니다.

 

UpdateBatch 메서드를 호출할 때만 공급자가 여러 가지 변경 내용을 캐시하여 기본 데이터 원본에 쓰는 '일괄 업데이트 모드'에서 OriginalValue 속성은 변경 작업 이전, 즉 마지막 UpdateBatch 메서드 호출 이후의 필드 값을 반환합니다. 이 값은 CancelBatch 메서드에서 Value 속성을 바꾸는 데 사용하는 값과 같습니다. 이 속성을 UnderlyingValue 속성과 함께 사용하면 일괄 업데이트로 인해 발생하는 충돌을 해결할 수 있습니다.

 

다음 코드는 OriginalValue 속성을 사용하는 간단한 예제입니다.

 

Sub TestADO()
    Dim conn As Object
    Dim rs As Object
    Dim connectionString As String
    Dim query As String
    Dim dbPath As String
    Dim tableName As String

    dbPath = "D:\download\Biblio.mdb"
    tableName = "Authors"

    Set conn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    ' 데이터베이스 연결 문자열 설정
    conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

    ' SQL 쿼리 설정
    query = "SELECT * FROM " & tableName


    rs.Open query, conn, 1, 3  ' adOpenKeyset (=1), adLockOptimistic (=3)

    If Not rs.EOF Then
        rs.MoveFirst

        ' AbsolutePosition 속성을 사용하여 특정 위치로 이동합니다.
        If rs.RecordCount >= 3 Then
            rs.AbsolutePosition = 3

            ' 필드 값을 변경합니다.
            rs.Fields("Author").Value = "Boddie, John"   ' 새로운 값으로 교체

            Debug.Print "=== Before Update ==="
            Debug.Print "Original Value: " & rs.Fields("Author").OriginalValue
            Debug.Print "New Value: " & rs.Fields("Author").Value

            ' Update 메서드를 호출하여 데이터베이스에 변경사항을 적용합니다.
            rs.Update

            Debug.Print "=== After Update ==="
            Debug.Print "Original Value after Update: " & rs.Fields("Author").OriginalValue
            Debug.Print "New Value after Update: " & rs.Fields("Author").Value
        Else
        End If

    End If

    If Not (rs Is Nothing) Then
        If (rs.State And 1) = 1 Then
            rs.Close
        End If
        Set rs = Nothing
    End If

    If conn.State = 1 Then conn.Close
    Set conn = Nothing
End Sub

' 출력 결과
' === Before Update ===
' Original Value: Doe , John
' New Value: Boddie, John
' === After Update ===
' Original Value after Update: Boddie, John
' New Value after Update: Boddie, John

Type property

Parameter, Field 또는 Property 개체의 작업 유형이나 데이터 형식을 나타냅니다.

 

설정 및 반환 값
DataTypeEnum 값을 설정하거나 반환합니다.

 

DataTypeEnum - ActiveX Data Objects (ADO)

DataTypeEnum

learn.microsoft.com

주의
Parameter 개체의 경우 Type 속성은 읽기/쓰기가 가능합니다. Record의 Fields 컬렉션에 추가된 새 Field 개체의 경우 Field의 Value 속성을 지정하고 데이터 공급자가 Fields 컬렉션의 Update 메서드를 호출하여 새 Field를 추가한 후에만 Type은 읽기/쓰기가 가능합니다.

다른 모든 개체의 경우 Type 속성은 읽기 전용입니다.

다음은 Employees 테이블에 있는 모든 Field 개체의 Type 속성 값에 해당하는 상수 이름을 표시하여 Type 속성을 보여 주는 예제입니다.

Sub Main()
    On Error GoTo ErrorHandler
    
    Dim Cnxn As ADODB.Connection
    Dim rstEmployees As ADODB.Recordset
    
    ' Open a connection to the database
    Set Cnxn = OpenDatabaseConnection("MySqlServer", "Pubs")
    
    ' Open the Employees table as a recordset
    Set rstEmployees = OpenTableRecordset(Cnxn, "employee")
    
    ' List fields in the Employees table
    ListFieldsInTable rstEmployees
    
    ' Clean up
     CloseRecordsetAndConnection rstEmployees, Cnxn
    Exit Sub

ErrorHandler:
    ' Clean up in case of error
    CloseRecordsetAndConnection rstEmployees, Cnxn
    
    If Err <> 0 Then
        MsgBox Err.Source & "-->" & Err.Description, , "Error"
    End If
End Sub

Function OpenDatabaseConnection(ServerName As String, DatabaseName As String) As ADODB.Connection
    Dim Cnxn As ADODB.Connection
    Set Cnxn = New ADODB.Connection
    
    ' Create the connection string
    Dim strCnxn As String
    strCnxn = "Provider='sqloledb';Data Source='" & ServerName & "';" & _
        "Initial Catalog='" & DatabaseName & "';Integrated Security='SSPI';"
    
    ' Open the connection
    Cnxn.Open strCnxn
    
    Set OpenDatabaseConnection = Cnxn
End Function

Function OpenTableRecordset(Cnxn As ADODB.Connection, TableName As String) As ADODB.Recordset
    Dim rst As ADODB.Recordset
    Set rst = New ADODB.Recordset
    
    ' Open the recordset with data from the specified table
    rst.Open TableName, Cnxn, , , adCmdTable
    
    Set OpenTableRecordset = rst
End Function

Sub ListFieldsInTable(rst As ADODB.Recordset)
    Debug.Print "Fields in Table:" & vbCr
    
    Dim fld As ADODB.field
    Dim FieldType As String
    
    ' Enumerate Fields collection of the table
    For Each fld In rst.Fields
        ' Translate field-type code to text
        Select Case fld.Type
            Case adChar
               FieldType = "adChar"
            Case adVarChar
               FieldType = "adVarChar"
            Case adSmallInt
               FieldType = "adSmallInt"
            Case adUnsignedTinyInt
               FieldType = "adUnsignedTinyInt"
            Case adDBTimeStamp
               FieldType = "adDBTimeStamp"
        End Select
        ' Display field information
        Debug.Print "  Name: " & fld.Name & vbCr & _
          "  Type: " & FieldType & vbCr
    Next fld
End Sub

Sub CloseRecordsetAndConnection(ByRef rst As ADODB.Recordset, ByRef Cnxn As ADODB.Connection)
    If Not rst Is Nothing Then
        If rst.State = adStateOpen Then rst.Close
        Set rst = Nothing
    End If

    If Not Cnxn Is Nothing Then
        If Cnxn.State = adStateOpen Then Cnxn.Close
        Set Cnxn = Nothing
    End If
End Sub

' 출력 결과
' Fields in Table:

' Name:   emp_id
'   Type: adChar

' Name:   fname
'   Type: adVarChar

' Name:   minit
'   Type: adChar

' Name:   lname
'   Type: adVarChar

' Name:   job_id
'   Type: adSmallInt

' Name:   job_lvl
'   Type: adUnsignedTinyInt

' Name:   pub_id
'   Type: adChar

' Name:   hire_date
'   Type: adDBTimeStamp

UnderlyingValue property

데이터베이스에 있는 Field 개체의 현재 값을 나타냅니다.

 

반환 값
Field의 값을 나타내는 Variant 값을 반환합니다.

 

다음은 OriginalValue 및 UnderlyingValue 속성을 보여 주는 예제입니다. 여기에서는 Recordset 일괄 업데이트 중 레코드의 원본 데이터가 변경된 경우 메시지를 표시합니다.

Public Sub Main()
    On Error GoTo ErrorHandler

    Dim Cnxn As ADODB.Connection
    Dim rstTitles As ADODB.Recordset
    Dim fldType As ADODB.Field
    Dim strCnxn As String

    ' Open connection.
    Set Cnxn = CreateConnection(strCnxn)

    ' Open recordset for batch update.
    Set rstTitles = CreateRecordSet(Cnxn, "titles")

    ' Set field object variable for Type field.
    Set fldType = rstTitles!Type

    ' Change the type of psychology titles.
    ChangeTitleTypes rstTitles, fldType

    ' Simulate a change by another user by updating data using a command string.
    UpdateTitleTypes Cnxn

    ' Check for changes.
    CheckForChanges rstTitles, fldType

    ' Cancel the update because this is a demonstration and restore original values.
    CancelBatchAndUpdate rstTitles, Cnxn

    CleanUp rstTitles, Cnxn

    Exit Sub

ErrorHandler:
    HandleError rstTitles, Cnxn

End Sub

Function CreateConnection(strCnxn As String) As ADODB.Connection
    Set CreateConnection = New ADODB.Connection
    strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
              "Initial Catalog='Pubs';Integrated Security='SSPI';"
    CreateConnection.Open strCnxn
End Function

Function CreateRecordSet(Cnxn As ADODB.Connection, strSQLTable As String) As ADODB.Recordset
    Set CreateRecordSet = New ADODB.Recordset
    With CreateRecordSet
        .ActiveConnection = Cnxn
        .CursorType = adOpenKeyset
        .LockType = adLockBatchOptimistic
        .Open strSQLTable
    End With
End Function

Sub ChangeTitleTypes(rst As Recordset, fld As Field)
    Do Until rst.EOF
        If Trim(fld) = "psychology" Then
            fld = "self_help"
        End If
        rst.MoveNext
    Loop
End Sub

Sub UpdateTitleTypes(cxn As Connection)
    cxn.Execute "UPDATE Titles SET type ='sociology' WHERE type ='psychology'"
End Sub

Sub CheckForChanges(rst As Recordset, fld As Field)
    rst.MoveFirst
    Do Until rst.EOF
        If fld.OriginalValue <> fld.UnderlyingValue Then
            MsgBox "Data has changed!" & vbCr & vbCr & _
                 "  Title ID: " & rst!title_id & vbCr & _
                 "  Current value: " & fld & vbCr & _
                 "  Original value: " & _
                   fld.OriginalValue & vbCr & _
                 "  Underlying value: " & _
                   fld.UnderlyingValue & vbCr
        End If
        rst.MoveNext
    Loop
End Sub

Sub CancelBatchAndUpdate(rst As Recordset, cxn As Connection)
    rst.CancelBatch
    cxn.Execute "UPDATE Titles SET type ='psychology' WHERE type ='sociology'"
End Sub

Sub CleanUp(rst As Recordset, cnx As Connection)
    If Not rst Is Nothing Then If rst.State = adStateOpen Then rst.Close
    If Not cnx Is Nothing Then If cnx.State = adStateOpen Then cnx.Close

    Set rst = Nothing
    Set cnx = Nothing

End Sub

Sub HandleError(rst As Recordset, cxn As Connection)

    CleanUp rst, cxn

    If Err <> 0 Then MsgBox Err.Source & "-->" & Err.Description, , "Error"

    Err.Clear

End Sub

 

 

Value property

Field, Parameter 또는 Property 개체에 할당된 값을 나타냅니다.

설정 및 반환 값
개체의 값을 나타내는 Variant 값을 설정하거나 반환합니다. 기본값은 Type 속성에 따라 다릅니다.

비고
Value 속성을 사용하여 Field 개체의 데이터를 설정 또는 반환하거나, Parameter 개체로 매개 변수 값을 설정 또는 반환하거나, Property 개체로 속성 설정을 설정 또는 반환합니다. Value 속성이 읽기/쓰기가 가능한지 읽기 전용인지는 다양한 요소에 의해 결정됩니다. 자세한 내용은 해당 개체 항목을 참고하십시오.

ADO를 사용하면 Value 속성으로 긴 이진 데이터를 설정하고 반환할 수 있습니다.

 

참고
Parameter 개체의 경우 ADO는 공급자에서 Value 속성을 한 번만 읽습니다. 명령에 Value 속성이 비어 있는 Parameter가 있을 경우 해당 명령에서 Recordset을 만들려면 먼저 Recordset을 닫은 다음 Value 속성을 검색해야 합니다. 그렇지 않으면 일부 공급자에 대해 Value 속성이 비어 있거나 올바른 값이 포함되지 않을 수 있습니다.

Record 개체의 Fields 컬렉션에 추가된 새 Field 개체의 경우, Value 속성을 먼저 설정해야 다른 Field 속성을 지정할 수 있습니다. 먼저 Value 속성에 특정 값을 지정하고 Fields 컬렉션의 Update를 호출해야 합니다. 그런 다음 Type, Attributes 등의 다른 속성에 액세스할 수 있습니다.

다음은 Employees 테이블의 필드와 속성 값을 표시하여 Field 및 Property 개체의 Value 속성을 보여 주는 예제입니다.

Public Sub Main()
    On Error GoTo ErrorHandler

    Dim Cnxn As ADODB.Connection
    Dim rstEmployees As ADODB.Recordset
    Dim strCnxn As String

    ' Open connection.
    Set Cnxn = CreateConnection(strCnxn)

    ' Open recordset with data from Employees table.
    Set rstEmployees = CreateRecordSet(Cnxn, "employee")

    ' Print field values in rstEmployees.
    PrintFieldValues rstEmployees

    ' Print property values in rstEmployees.
    PrintPropertyValues rstEmployees

    CleanUp rstEmployees, Cnxn

    Exit Sub

ErrorHandler:
    HandleError rstEmployees, Cnxn

End Sub

Function CreateConnection(strCnxn As String) As ADODB.Connection
    Set CreateConnection = New ADODB.Connection
    strCnxn = "Provider='sqloledb';Data Source='MySqlServer';" & _
              "Initial Catalog='Pubs';Integrated Security='SSPI';"
    CreateConnection.Open strCnxn
End Function

Function CreateRecordSet(Cnxn As ADODB.Connection, strSQLTable As String) As ADODB.Recordset
    Set CreateRecordSet = New ADODB.Recordset
    With CreateRecordSet
        .Open strSQLTable, Cnxn, , , adCmdTable
    End With
End Function

Sub PrintFieldValues(rst As Recordset)
    Dim fld As Field
    Debug.Print "=================== Field Values ==================="
    For Each fld In rst.Fields
        Debug.Print "   " & fld.Name & " = " & fld.Value
    Next fld
    '    Debug.Print "===================================================="
End Sub

Sub PrintPropertyValues(rst As Recordset)
    Dim prp As Property
    Debug.Print "================= Property Values =================="
    For Each prp In rst.Properties
        Debug.Print "   " & prp.Name & "=" & prp.Value
    Next prp
    ' Debug.Print "===================================================="
End Sub


Sub CleanUp(rst As Recordset, cxn As Connection)
    If Not rst Is Nothing Then If rst.State = adStateOpen Then rst.Close
    If Not cxn Is Nothing Then If cxn.State = adStateOpen Then cxn.Close

    Set rst = Nothing
    Set cxn = Nothing

End Sub

Sub HandleError(rst As Recordset, cxn As Connection)

    CleanUp rst, cxn

    If Err <> 0 Then MsgBox Err.Source & "-->" & Err.Description, , "Error"

    Err.Clear

End Sub

 

도움말 출처

 

 

Field properties, methods, and events (ADO)

Office developer client VBA reference documentation

learn.microsoft.com

 

'ActiveX Data Objects (ADO)' 카테고리의 다른 글

Fields Collection  (0) 2023.10.02
Recordset Object  (0) 2023.09.30
Connection Object  (0) 2023.08.31