簡體   English   中英

如何使用c#代碼在MS-Access數據庫中查找表的標識列名稱?

[英]How to find Identity column name of a table in MS-Access database using c# Code?

我想使用c#代碼找出MS-Access數據庫中表的標識列名稱。

請幫我。

這段代碼是我的o / r-mapper的一部分

private string RetrieveAutoNumberColumn(OleDbConnection cnn, TableSchema tableSchema)
{
    OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + tableSchema.TableName + "] WHERE False", cnn);
    DataTable dtSchema = adapter.FillSchema(new DataTable(), SchemaType.Source);
    if (dtSchema == null) {
        throw new UnimatrixMappingException("Table \"" + tableSchema.TableName + "\" not found. Connection = " + this._connectString);
    }
    string columnName = null;
    for (int i = 0; i < dtSchema.Columns.Count; i++) {
        if (dtSchema.Columns[i].AutoIncrement) {
            columnName = dtSchema.Columns[i].ColumnName;
            break;
        }
    }
    return columnName;
}

像這樣創建連接

var cnn = new OleDbConnection(
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\Data\MyDatabase.mdb\";OLE DB Services=-1");

您可以像這樣檢索主鍵(不一定與“自動編號”列相同)

private static void RetrievePrimaryKeyInfo(OleDbConnection cnn, TableSchema tableSchema, string[] restrictions)
{
    using (DataTable dtPrimaryKeys = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, restrictions)) {
        foreach (DataRow row in dtPrimaryKeys.Rows) {
            string columnName = (string)row["COLUMN_NAME"];
            //TODO:  Do something useful with columnName here
        }
    }
}

restrictions定義為

string[] restrictions = new string[] { null, null, tableName };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM