Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

c# - Check if column exists in OleDb table

I am trying to check if a column exists and if not, add it. I've tried a couple of solutions including this, but the syntax isn't correct for Access db.

This is what I have so far:

    public void Update(string task, string dbPath, string tableName = "Frames")
    {
        OleDbConnection db = new OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;data source=" + dbPath);
        db.Open();

        OleDbCommand command = db.CreateCommand();
        command.CommandText = "COL_LENGTH('Frames','SetNumber')";
        Debug.WriteLine(command.ExecuteReader());




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

        DataTable dtColumns = db.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, restrictions);

        foreach (DataColumn column in dtColumns.Columns)
        {
            Debug.WriteLine(column.ColumnName);
        }*/

    }

I also tried using GetOleDbSchemaTable but it isn't returning the right table or something. What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
} 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...