2012-02-24 72 views
2

我需要我的程序檢查指定的列是否存在於MS Access 2000數據庫中,如果不存在 - 請添加它。我使用.NET Framework 2.0 我試圖使用oleDbConnection.GetSchema()方法,但無法在元數據中找到列名(我真的不是專業版,呵呵)和msdn上的任何規範。 我將不勝感激任何幫助。如何檢查MS Access數據庫中是否存在指定的列?

感謝您的回答。 這裏是溶液我在代碼中使用:

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

回答

0

這是代碼,是我的O/R映射器的一部分。你不能使用它,因爲它取決於其他類,但我希望你能得到圖片。這樣

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

定義限制,這從一個表

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); 
     } 
    } 
} 
+0

感謝檢索列!這足以讓我創建一個我需要的快速和骯髒的解決方案=) – user1231379 2012-02-24 19:18:29

相關問題