Use of OleDbDataAdapter and OleDbCommandBuilder to gret and update DataTables in C#

Owen Ransen 546 Reputation points
2022-06-28T08:12:35.207+00:00

I'm really inexpert in database and OLE stuff, but I've managed to find (after a ton of searchng) enough explanation to write GetDataTable and UpdateDataTable functions.

My question is: Have I missed something here below which will bite me in the future?

    public static void UpdateDataTable (DataTable dt)  
    {  
        try  
        {  
            OpenDbConnections();  
  
            string strSQL = "SELECT * FROM " + dt.TableName;  
  
            OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQL, m_DbDataConnection);  
  
            OleDbCommandBuilder myCmdBuilder = new OleDbCommandBuilder(myCmd);  
  
            myCmdBuilder.GetInsertCommand(); // So dt.Add works  
            myCmdBuilder.GetDeleteCommand(); // So a dt row.Delete works  
            myCmdBuilder.GetUpdateCommand(); // so a dt row.BeginEdit and row.EndEdit works  
  
            myCmd.Update(dt);  
        }  
        catch (Exception Ex)  
        {  
            ABSup.Log.WriteLn(CLog.Type_e.ekErr, "UpdateTable failed <" + dt.TableName + ">\n" +  
                                                  Ex.Message, "\n", ABSup.m_sTableDBFullFilename,  
                                                 "\nHRESULT:", Ex.HResult.ToString());  
        }  
    }  
  
  
  
    // Get a named table from the database...  
    // Tables are normally in DB_CreaColl.mdb  
    public static DataTable GetDataTable (string sTableName)  
    {  
        try  
        {  
            OpenDbConnections();  
  
            string strSQL = "SELECT * FROM " + sTableName;  
  
            OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQL, m_DbDataConnection);  
            DataSet dtSet = new DataSet();  
            myCmd.Fill(dtSet, sTableName);  
            DataTable tabData = dtSet.Tables[0];  
            return tabData;  
        }  
        catch (Exception Ex)  
        {  
            ABSup.Log.WriteLn(CLog.Type_e.ekErr, "GetDataTable could not open <" + sTableName + ">\n" +   
                                                  Ex.Message, "\n", ABSup.m_sTableDBFullFilename,  
                                                 "\nHRESULT:", Ex.HResult.ToString());  
            return null;  
        }  
    }  

PS: I've also tried to add the above code in the 101010 code window, but it does not work...

Developer technologies .NET .NET Runtime
Developer technologies C#
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2022-06-29T19:31:03.923+00:00

    My question is: Have I missed something here below which will bite me in the future?

    The DataTable is/was a ASP.NET generic data container that's not found much in modern C# programming. Strong types and Generics are preferred. After all C# is a strongly typed language. Also, the DataTable is an ASP.NET construct that does not translate well to other platforms/clients. For example, if you decided to share you data access layer over REST services (Web API), only ASP.NET clients will understand what a DataTable is. Even then the ASP.NET client might not know if they have a Widget result set or a FooBar result set.

    In my opinion you're better off using the OleDbDataReader to populate a List<T> (C# Generics).


2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-06-29T06:59:47.213+00:00

    GetDataTable should use assertion rather than a try/catch, something like the following which requires the connection string to be setup by you.

    using System;  
    using System.Data;  
    using System.Data.OleDb;  
    using System.Linq;  
      
    namespace YourNamespaceGoesHere  
    {  
        public class Utilities  
        {  
            private static string _connectionString =   
                "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TODO";  
      
            public static bool TableExists(string tableName)  
            {  
                using (var cn = new OleDbConnection() { ConnectionString = _connectionString })  
                {  
                    var schema = cn.GetOleDbSchemaTable(  
                        OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });  
      
                    return schema.Rows.OfType<DataRow>().Any(r =>   
                        string.Equals(r.ItemArray[2].ToString(), tableName,   
                            StringComparison.CurrentCultureIgnoreCase));  
                }  
            }  
        }  
    }  
      
    

    Also, its a bad idea to have a method such as OpenDbConnections(); which appears to open database connection(s). Best to create a new connection when possible, meaning in some cases it's not possible while in other cases a connection is private to a method.


  2. Lamia Elshahat Eldesoky 76 Reputation points
    2022-07-01T15:25:56.573+00:00

    That's great

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.