Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

ADO.NET - Succinctly populating a DataTable (See related posts)

From code supporting article at http://msdn.microsoft.com/msdnmag/issues/06/08/DesignPatterns/default.aspx

    public class DatabaseGateway
    {
        public DataTable QueryForDataTable(string expression)
        {
            using (IDatabaseConnection connection = new DatabaseConnection())
            {
                DataTable table = new DataTable();

                using (IDataReader reader = connection.CreateCommandFor(expression).ExecuteReader())
                {
                    table.Load(reader);
                }

                return table;
            }
        }
    }

    public class DatabaseConnection : IDatabaseConnection
    {
        public IDbCommand CreateCommandFor(string dynamicSqlExpression)
        {
            IDbCommand command = underlyingConnection.CreateCommand();
            command.CommandType = CommandType.Text;
            command.CommandText = dynamicSqlExpression;
            return command;
        }

        public void Dispose()
        {
            underlyingConnection.Close();
            underlyingConnection.Dispose();
            underlyingConnection = null;
        }


        // ...
    }

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts