【问题标题】:conn.GetSchema find primary key of table - MsAccessconn.GetSchema 查找表的主键 - MsAccess
【发布时间】:2023-03-20 21:09:01
【问题描述】:

我有一个位于 D 盘的 MsAccess 数据库 (.mdb) (D:\project.mdb)。 数据库有 120 多个表。有一个表Records,它有主键和多个字段。我想获取 Columns、ColumnType 和 PrimaryKey。

我正在使用以下方法获取字段及其类型:

Dim TableNm_ As String = "Records"      
Dim restrictions2() As String = {Nothing, Nothing, TableNm_, Nothing} 
Dim DataTable2 As System.Data.DataTable = conn.GetSchema("Columns", restrictions2)

但它没有 PrimayKey 列。

我浏览了几篇 SO 帖子和其他类似 GetSchema and PrimaryKey column 的帖子。但我想创建一个命令和 Reader 来读取密钥。

有没有办法只使用 conn.GetSchema 获取表 Records 的 PrimayKey 列?

【问题讨论】:

  • 连接不知道表的架构。但是使用 DataReader,您可以使用 .GetSchemaTable 方法。

标签: .net database vb.net ms-access oledb


【解决方案1】:

您可以使用Connection.GetOleDbSchemaTable 并传递 PrimaryKeys SchemaGuid。 对 TableName 应用限制为:

DataTable2 = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, New String() {Nothing, Nothing, TableNm_}) 
For Each TableRow As DataRow In DataTable2.Rows
    If TableRow.Item("PK_NAME").ToString.ToLower = "PrimaryKey".ToLower Then
        Dim  PrimaryKey = TableRow.Item("COLUMN_NAME")
        Dim Ordinal = CShort(TableRow.Item("ORDINAL"))
    End If
Next

【讨论】:

    【解决方案2】:

    你可以从Kros.Utils.MsAccess使用DatabaseSchema

    using(var cn = new OleDbConnection("MS Access Connection String"))
    {  
      DatabaseSchema schema = DatabaseSchemaLoader.Default.LoadSchema(cn);
      Assert.IsFalse(schema.Tables["Person"].Columns["Id"].AllowNull);
    }
    

    包含有关表、列、索引...的信息

    【讨论】:

      猜你喜欢
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 2012-05-15
      • 2021-12-08
      相关资源
      最近更新 更多