如何在C#中获取Ms Access表的主键

问题描述:

给定一个连接和一个tableName,我需要一个或多个字段(只需字段名即可),它们构成Microsoft Access表的主键.

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.

好的,我想我找到了.它应该适用于所有oledb并且是…….像:

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