简体   繁体   中英

How do I check if specified column exists in MS Access database?

I need my program check if specified column exists in MS Access 2000 database, and if it doesn't - add it. I use .NET Framework 2.0 I tried to use oleDbConnection.GetSchema() method, but couldn't find column names in metadata (i'm really not a pro, huh) and any specification on msdn. I would appreciate any help.

Thanks for answers. Here is solution i used in my code:

bool flag = false; string[] restrictions = new string[] { null, null, mytable };
DataTable dtColumns = oleDbConnection1.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Columns, restrictions);
foreach (DataRow row in dtColumns.Rows) 
{ 
    if (mycolumnname==(string)row["COLUMN_NAME"]) flag = true;
}

This is code that is part of ao/r-mapper of mine. You cannot use it as is beacuse it depends on other classes, but I hope you get the picture.

Define restrictions like this

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

This retrieves the columns from a table

private void RetrieveColumnInfo(OleDbConnection cnn, TableSchema tableSchema,
          string[] restrictions, Func<string, string> prepareColumnNameForMapping)
{
    using (DataTable dtColumns = 
                 cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, restrictions)) {
        string AutoNumberColumn = RetrieveAutoNumberColumn(cnn, tableSchema);
        foreach (DataRow row in dtColumns.Rows) {
            var col = new TableColumn();
            col.ColumnName = (string)row["COLUMN_NAME"];
            try {
                col.ColumnNameForMapping =
                    prepareColumnNameForMapping(col.ColumnName);
            } catch (Exception ex) {
                throw new UnimatrixExecutionException(
                    "Error in delegate 'prepareColumnNameForMapping'", ex);
            }
            col.ColumnAllowsDBNull = (bool)row["IS_NULLABLE"];
            col.ColumnIsIdentity = col.ColumnName == AutoNumberColumn;
            DbColumnFlags flags = (DbColumnFlags)(long)row["COLUMN_FLAGS"];
            col.ColumnIsReadOnly =
                col.ColumnIsIdentity ||
                (flags & (DbColumnFlags.Write | DbColumnFlags.WriteUnknown)) ==
                                                               DbColumnFlags.None;
            if (row["CHARACTER_MAXIMUM_LENGTH"] != DBNull.Value) {
                col.ColumnMaxLength = (int)(long)row["CHARACTER_MAXIMUM_LENGTH"];
            }
            col.ColumnDbType = GetColumnDbType((int)row["DATA_TYPE"]);
            col.ColumnOrdinalPosition = (int)(long)row["ORDINAL_POSITION"];
            GetColumnDefaultValue(row, col);

            tableSchema.ColumnSchema.Add(col);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM