Solved

Adding columns to a DataTable in C#

Posted on 2013-05-16
5
287 Views
Last Modified: 2013-05-21
I need to create a DataTable where the column definitions are being retrieved from an Oracle Database schema.  I am able to successfully get the information I need but where I run into a problem is setting the DataType on the column.

Here is my code so far:
        public DataTable CreateTable(OracleConnection connectionObj, String owner, String tblname)
        {
            // Creates a DataTable with Table Definition pulled from database schema.
            // Assumptions:  
            //      Works only with Oracle Databases
            //      Database already opened and user has privileges to access schema info
            // Returns:
            //      Returns specified datatable on success, otherwise returns null

            DataTable DT = new DataTable();
            DataColumn column;

            // Check that the database has been opened
            if (connectionObj == null || connectionObj.State != ConnectionState.Open)
                return null;

            // Create Command object
            OracleCommand command = connectionObj.CreateCommand();
            command.Connection = connectionObj;

            // Create Reader
            OracleDataReader reader;
            try
            {
                // Retrieve Table Definition
                command.CommandText =
                    "SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE " +
                    "FROM ALL_TAB_COLUMNS " +
                    "WHERE OWNER=:Owner AND TABLE_NAME=:Tblname";

                // Remove any previously set Parameters
                command.Parameters.Clear();
                command.Parameters.Add("Owner", OracleDbType.Varchar2, owner, ParameterDirection.Input);
                command.Parameters.Add("Tblname", OracleDbType.Varchar2, tblname, ParameterDirection.Input);

                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    column = new DataColumn((string)reader["COLUMN_NAME"]);
                    column.DataType = (string)reader["DATA_TYPE"];    <---- This is where I need help
                    column.MaxLength = (Int32)reader["DATA_LENGTH"];
                   DT.Columns.Add(column);
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                reader.Close();
                command.Dispose();
                reader.Dispose();
                column.Dispose();
            }

            return DT;
        }

Open in new window


What I can't figure out is how to set the DataType given the string value in the record returned.  Examples that I have seen use something like the following:  column.DataType = System.Type.GetType("System.Int32");

I was hoping there would be an easy way without having to use a Switch statement looking for all the valid Oracle types.

Any help is greatly appreciated!
0
Comment
Question by:dyarosh
  • 2
  • 2
5 Comments
 
LVL 11

Expert Comment

by:Mihai Stancescu
ID: 39175707
Hi,

Indeed you can use a helper method that translates the Oracle types to .NET types or you can use a OracleDataAdapter.Fill method to automatically create the columns for you. You can return only one row with nulls or whatever dummy data and delete it before inserting actual data.


Hope this helps,
Mishu
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 39176774
are you using NET Framework Data Provider for Oracle, or Oracle Data Provider for .NET?
0
 

Author Comment

by:dyarosh
ID: 39181365
I am using Oracle.DataAccess.  

Mishu007 - What is the helper method that you refer to?  I don't want to use the OracleDataAdapter.Fill method because I don't want the data just the schema unless there is a way to get just the schema with the OracleDataAdapter.
0
 
LVL 11

Accepted Solution

by:
Mihai Stancescu earned 500 total points
ID: 39183450
Hi,

You can use the Fill method if you do a select like "select * from <Table> where 1=0", this way the where clause is false and the top row is returned. Unfortunately I can only test this on Sql Server but on Oracle should work the same.



Regards,
Mishu
0
 

Author Closing Comment

by:dyarosh
ID: 39185471
Awesome.  Worked like a charm and gave me exactly what I needed.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now