2013年6月9日 星期日

Get Column Name and Data Types of Access Tables

參考引用
--
Private Sub Demo(ByVal ConnectionString As String)
   Using cn As New OleDbConnection(ConnectionString)
      Dim Result = SchemaInfo(cn.ConnectionString, "Table1")
      For Each row As DataRow In Result.Rows
         Console.WriteLine("Name={0} Type={1}", row("ColumnName"), row("DataType"))
      Next
   End Using
End Sub
Public Function SchemaInfo(ByVal ConnectionString As String, ByVal TableName As String) As DataTable
   Dim dt As New DataTable With {.TableName = "Schema"}

   dt.Columns.AddRange( _
      New DataColumn() _
         { _
            New DataColumn("ColumnName", GetType(System.String)), _
            New DataColumn("DataType", GetType(System.String)) _
         } _
      )

   Using cn As New OleDbConnection(ConnectionString)
      Using cmd As New OleDbCommand("SELECT * FROM " & TableName, cn)
         cn.Open()
         Dim Reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.KeyInfo)
         Dim schemaTable = Reader.GetSchemaTable()
         schemaTable.TableName = "TableSchema"

         Dim sw As New IO.StringWriter
         schemaTable.WriteXml(sw)
         Dim Doc = New XDocument
         Doc = XDocument.Parse(sw.ToString)
         Dim query = _
            ( _
               From T In Doc... _
               Select _
                  Name = T..Value, _
                  DataType = T..Value.Split(","c)(0).Replace("System.", "") _
            ).ToList

         For Each item In query
            Dim Row As DataRow
            Row = dt.NewRow
            Row("ColumnName") = item.Name
            Row("DataType") = item.DataType
            dt.Rows.Add(Row)
         Next

      End Using
   End Using

   Return dt

End Function

沒有留言:

張貼留言