Check if column exists in OleDb table

心不动则不痛 提交于 2019-11-29 12:07:34

To check if a column exist in a datatable you could use the GetSchema method of the OleDbConnection

public void Update(string task, string dbPath, string colName, string tableName = "Frames") 
{ 
    using(OleDbConnection db = new OleDbConnection("........"))
    {
        db.Open(); 
        var schema = db.GetSchema("COLUMNS"); 
        var col = schema.Select("TABLE_NAME='" + tableName + 
                   " AND COLUMN_NAME='" + colName + "'" 

        if(col.Length > 0)
           // Column exist
        else
           // Column doesn't exist
} 

Your approach with GetOleDbSchemaTable is the way to go. Each row of the schema table contains the information for a single column of your table and each column of the schema table represents one property of it. So, loop through the rows of the schema table, not the columns!

foreach (DataRow row in dtColumns.Rows) { // <== dtColumns.Rows
                                          //     (NOT dtColumns.Columns)
    string columnName = (string)row["COLUMN_NAME"];
    ....
}

Your approach yields the column names of the schema table itself.

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