office交流网--QQ交流群号

Access培训群:792054000         Excel免费交流群群:686050929          Outlook交流群:221378704    

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

Access 使用DAO及ADO创建数据表主键PrimaryKey的不同方法对比

2017-07-13 21:51:00
ADAM-Office中国
原创
4663

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
分享