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

VB 列出SQL数据库中所有表及字段信息

 程序思想:用Select name From sysobjects Where xtype = 'u'得到所有表,然后循环打开表,根据 Rs_Colums.Fields(I).Name 得到字段名, FieldType(Rs_Colums.Fields(I).Type) 得到字段类型, Rs_Colums.Fields(I).DefinedSize 宽度
  由于Rs_Colums.Fields(I).Type返回类型是数字,程序中写了一个FieldType函数转化成中文类型。

Private Sub Command1_Click()
 Dim Cn
As New ADODB.Connection
 Dim Rs_Table
As New ADODB.Recordset
 Dim Rs_Colums
As New ADODB.Recordset
  
 With Cn 
'定义连接
  .CursorLocation = adUseClient
  .Provider =
"sqloledb"
  .Properties("Data Source").Value = "LIHG"
  .Properties("Initial Catalog").Value = "NorthWind"
  .Properties("User ID") = "sa"
  .Properties("Password") = "sa"
  .Properties("prompt") = adPromptNever
  .ConnectionTimeout =
15
  .Open
  
  If .State = adStateOpen
Then
  Rs_Table.CursorLocation = adUseClient  '得到所有表名
  Rs_Table.Open "Select name From sysobjects Where xtype = 'u'", Cn, adOpenDynamic, adLockReadOnly
  Rs_Table.MoveFirst
  Do
While Not Rs_Table.EOF
  Debug.Print Rs_Table.Fields(
"name")
  Rs_Colums.CursorLocation = adUseClient
  Rs_Colums.Open
"select top 1 * from [" & Rs_Table.Fields("name") & "]", Cn, adOpenStatic, adLockReadOnly
  For I =
0 To Rs_Colums.Fields.Count - 1  ' 循环所有列
  Debug.Print Rs_Colums.Fields(I).Name  '字段名
  Debug.Print FieldType(Rs_Colums.Fields(I).Type) '字段类型
  Debug.Print Rs_Colums.Fields(I).DefinedSize '宽度
  Next
  Rs_Colums.Close
  Rs_Table.MoveNext
  Loop
  Rs_Table.Close
  Set Rs_Colums =
Nothing
  Set Rs_Table = Nothing