利用ADOX创建本地ACCESS数据库的问题,请高手指点一下。
我想通过一个循环来创建表中的各个字段,请问一下下面的代码错在哪?
总是执行到:TargetTable.Columns.Append TargetCols(I)这一句出错,说是“类型无效”。
Dim SourceDB As New ADOX.Catalog, SourceTable As New ADOX.Table, SourceCols() As New ADOX.Column
Dim TargetDB As New ADOX.Catalog, TargetTable As New ADOX.Table, TargetCols() As New ADOX.Column
conn.Open connString
Dim FilePath As String, DBFile As String, FieldCount As Integer, I As Integer
FilePath = App.Path
If Right(FilePath, 1) <> "\ " Then FilePath = FilePath & "\ "
DBFile = FilePath & "Test.MDB "
Set SourceDB.ActiveConnection = conn
TargetDB.Create "provider=microsoft.jet.oledb.4.0;data source= " & DBFile
Set SourceTable = SourceDB.Tables( "Test ")
TargetTable.Name = "Test "
TargetTable.ParentCatalog = TargetDB
TargetDB.Tables.Append TargetTable
FieldCount = SourceTable.Columns.Count - 1
ReDim SourceCols(FieldCount)
ReDim TargetCols(FieldCount)
For I = 0 To FieldCount
Set SourceCols(I) = SourceTable.Columns(I)
TargetCols(I).ParentCatalog = TargetDB
TargetCols(I).Type = SourceCols(I).Type
TargetCols(I).DefinedSize = SourceCols(I).DefinedSize
TargetCols(I).Name = SourceCols(I).Name
TargetTable.Columns.Append TargetCols(I)
Next
MsgBox "数据库已创建! ", vbInformation
[解决办法]
语法:
ADOX.Table.Columns.Append (Item,Type as DataTypeEnum,DefinedSize as Long)
Item是Field Name
Public Sub ADOCreateTable()
Dim cat As New ADOX.Catalog
Dim tbl As New ADOX.Table
' 打开catalog
cat.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=.\NorthWind.mdb; "
' 创建新的Table对象
With tbl
.Name = "Contacts "
.Columns.Append "ContactName ", adVarWChar
.Columns.Append "ContactTitle ", adVarWChar
.Columns.Append "Phone ", adVarWChar
.Columns.Append "Notes ", adLongVarWChar
.Columns( "Notes ").Attributes = adColNullable
End With
' 加入到Database
cat.Tables.Append tbl
Set cat = Nothing '释放
End Sub
[解决办法]
其实问题出在这一句:
TargetCols(I).Type = SourceCols(I).Type
SQL SERVER中的类型与ACCESS中的类型不完全相同,请注意类型的转换。