How to get the primary key of an Ms Access table in C#

前端 未结 1 2017
天涯浪人
天涯浪人 2021-01-07 08:08

I need the field or fields (just the name of the field will do) that form the primary key of a Microsoft Access Table, given a connection and a tableName.

相关标签:
1条回答
  • 2021-01-07 08:48

    ok, I guess I found it. It should work for all oledb and is sth. like :

    public static List<string> getKeyNames(String tableName, DbConnection conn)
        {
            var returnList = new List<string>();
    
    
            DataTable mySchema = (conn as OleDbConnection).
                GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys,
                                    new Object[] {null, null, tableName});
    
    
            // following is a lengthy form of the number '3' :-)
            int columnOrdinalForName = mySchema.Columns["COLUMN_NAME"].Ordinal;
    
            foreach (DataRow r in mySchema.Rows)
            {
                returnList.Add(r.ItemArray[columnOrdinalForName].ToString());
            }
    
            return returnList;
        }
    
    0 讨论(0)
提交回复
热议问题