如何检查访问数据库中是否存在表?

时间:2009-07-05 04:31:45

标签: ms-access vb6

如何检查表是否存在?

使用VB 6.0和ACCESS 2003

我的代码。

Cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & App.Path & "\iTDC-ACS.MDB"
Cn.Open

cmdCardEvent.ActiveConnection = Cn
cmd.ActiveConnection = Cn

cmdcardevent1.ActiveConnection = Cn
cmd.ActiveConnection = Cn

cmd.CommandText = "DROP TABLE tmp_cardevent"
cmd.Execute

cmd.CommandText = "drop table tmp_MOI"
cmd.Execute

这里我想检查表是否存在然后删除表,否则不需要。

如何检查表是否存在?

需要VB 6代码帮助吗?

3 个答案:

答案 0 :(得分:4)

Public Function IsExistingTable( _
      ByVal Database As String, _
      ByVal TableName As String _
   ) As Boolean

   Dim ConnectString As String
   Dim ADOXConnection As Object
   Dim ADODBConnection As Object
   Dim Table As Variant

   ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" & Database
   Set ADOXConnection = CreateObject("ADOX.Catalog")
   Set ADODBConnection = CreateObject("ADODB.Connection")
   ADODBConnection.Open ConnectString
   ADOXConnection.ActiveConnection = ADODBConnection
   For Each Table In ADOXConnection.Tables
      If LCase(Table.Name) = LCase(TableName) Then
         IsExistingTable = True
         Exit For
      End If
   Next
   ADODBConnection.Close

End Function

注意:在没有先检查的情况下执行DROP TABLE会更便宜。

答案 1 :(得分:2)

将此功能放在公共模块的下方。

调用函数的示例代码:

Dim result as boolean
result = IsExistingTable("c:\myFolder\myDatabase.mdb","myTableName")
If result Then
   'Do something
Else
   'Do something else.
Endif

答案 2 :(得分:0)

使用下面给出的On Error Resume Next示例。如果数据库中存在一个表(temp),那么它就会丢失,否则它将保留错误并转到下一条指令而不会出现任何错误。

On Error Resume Next
cmd.ActiveConnection = cn
cmd.CommandText = "drop table temp"
cmd.Execute , , adCmdText