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

只愿长相守 提交于 2019-12-19 04:58:11

问题


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:


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


来源:https://stackoverflow.com/questions/862749/how-to-get-the-primary-key-of-an-ms-access-table-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!