日期:2014-05-16  浏览次数:20946 次

ado连接access,如何获得一张表有多少个字段,以及每个字段的类型?
希望达到这样的目的,程序中并不知道表中有多少个字段,也不知道每个字段的名称和类型,。
希望可以读取出某一条记录每个字段下的相应值,放到一组cstring中的变量中去。
谢谢高手了~~~~

------解决方案--------------------
可以只用SQL语句获取表名,如下:

--列出所有的用户表

SELECT *
FROM MSysObjects
WHERE Flags=0 AND Type=1


但只用SQL语句无法获取表的字段名。


--下面代码列出指定表的所有字段名和文本类型字段的长度
'引用ADOX
'--> VBA窗口“工具”菜单
'--> 引用
'--> Microsoft ADO Ext. 2.X for DLL and Security

Public Sub list(strTblName As String)
Dim Cnn As New ADODB.Connection
Dim Fld As New ADOX.Column
Dim Cat As New ADOX.Catalog
Dim Tbl As New ADOX.Table

Set Cnn = CurrentProject.Connection

Set Cat.ActiveConnection = Cnn
Set Tbl.ParentCatalog = Cat
Set Tbl = Cat.Tables(strTblName)

Debug.Print "字段个数: " & Tbl.Columns.Count

For Each Fld In Tbl.Columns
Debug.Print "字段名: " & Fld.Name & ",宽度: " & Fld.DefinedSize & ",类型: " & Fld.Type
Next

End Sub
------解决方案--------------------
Dim Cnn As New ADODB.Connection
Dim fld As New ADOX.Column
Dim cat As New ADOX.Catalog
Dim Tbl As New ADOX.Table
Dim eert As New ADODB.Recordset
Set Cnn = CurrentProject.Connection
Set cat.ActiveConnection = Cnn
Set Tbl.ParentCatalog = cat
For Each jj In cat.Tables
MsgBox jj.Name & jj.Columns.Count
If UCase(Mid(jj.Name, 1, 2) <> "MS ") Then
For Each gh In jj.Columns
MsgBox gh.Name & gh.DefinedSize & gh.Type
eert.Open "select * from " & jj.Name, Cnn, adOpenDynamic, adLockOptimistic
Do While Not eert.EOF
For i = 0 To jj.Columns.Count - 1
MsgBox Nz(eert(i).Value, 0)
Next
eert.MoveNext
Loop
Next
End If
Next