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

I need a field or fields (field name only) that form the primary key of the Microsoft access table, given the join and table name.

+1


a source to share


1 answer


OK, I think I found it. It should work for all oledb and is sth. eg:



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;
    }

      

+4


a source







All Articles