office交流網--QQ交流群號

Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

Access 使用DAO及ADO創建數據錶主鍵PrimaryKey的不衕方法對比

2017-07-13 21:51:00
ADAM-Office中國
原創
4643

Access 使用DAO及ADO創建數據錶主鍵PrimaryKey的不衕方法對比,去來貼一箇吧


一、Access 使用DAO創建Access 數據錶主鍵PrimaryKey的代碼如下:



Sub DAOCreatePrimaryKey()
    Dim db      As DAO.Database
    Dim tbl     As DAO.TableDef
    Dim idx     As DAO.Index
    
    'Open the database
    Set db = DBEngine.OpenDatabase("C:\nwind.mdb")
    
    Set tbl = db.TableDefs("Contacts")
    
    ' Create the Primary Key and append table columns to it.
    Set idx = tbl.CreateIndex("PrimaryKey")
    idx.Primary = True
    idx.Fields.Append idx.CreateField("ContactId")
    
    ' Append the Index object to the Indexes collection of the TableDef.
    tbl.Indexes.Append idx
    db.Close
End Sub


二、Access 使用Ado創建Access 數據錶主鍵PrimaryKey的代碼如下:


ADOX

Sub ADOCreatePrimaryKey()
    Dim cat     As New ADOX.Catalog
    Dim tbl     As ADOX.Table
    Dim pk      As New ADOX.Key
    
    ' Open the catalog
    cat.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\nwind.mdb;"
    Set tbl = cat.Tables("Contacts")
        
    ' Create the Primary Key and append table columns to it.
    pk.Name = "PrimaryKey"
    pk.Type = adKeyPrimary
    pk.Columns.Append "ContactId"
    
    ' Append the Key object to the Keys collection of Table
    tbl.Keys.Append pk
    
    Set cat = Nothing
    
End Sub
分享