使用VB6检查MS Access数据库密钥

时间:2010-06-10 12:56:12

标签: ms-access vb6

如何使用Visual Basic 6.0和ms访问作为数据库检查现有表中的主键,组合键的数量?

2 个答案:

答案 0 :(得分:4)

一个表只有一个主键,可以是简单键或复合键。

答案 1 :(得分:2)

添加参考ADOX和ADODB库。

Function ShowKeys(tbl As String) As String
   'Add reference ADOX library:  Microsoft ADO Ext. 2.8 for DDL and Security.
   'Add reference ADODB library: Microsoft ActiveX Data Objects
   Dim cat As New ADOX.Catalog
   Dim tbl As ADOX.Table
   Dim idx As ADOX.Index
   Dim col As ADOX.Column
   Dim cnn As New ADODB.Connection

   On Error GoTo errh

   cnn.Open "Provider='Microsoft.Jet.OLEDB.4.0';" & _
        "Data Source= 'Northwind.mdb';"

   Set cat.ActiveConnection = cnn

   For Each tbl In cat.Tables
      If tbl.Name = tbl Then
         If tbl.Indexes.Count <> 0 Then
            For Each idx In tbl.Indexes
               With idx
                  If .PrimaryKey Then
                     For Each col In .Columns
                        ShowKeys = col.Name & ", " & ShowKeys
                     Next
                  End If
               End With
            Next
         End If
      End If
   Next

errh:
   If Err <> 0 Then
      MsgBox Err.Number & ": " & Err.Description, vbOKOnly, "Error"
   End If

   Set cat = Nothing
   Set tbl = Nothing
   Set idx = Nothing
   Set col = Nothing
   Set cnn = Nothing
End Function