Click here to Skip to main content
15,895,528 members
Home / Discussions / C#
   

C#

 
GeneralRe: How to Maximize Form.....??? Pin
S K Y11-Mar-09 16:52
S K Y11-Mar-09 16:52 
QuestionGetting this Error message....any one know y??? Pin
S K Y11-Mar-09 14:47
S K Y11-Mar-09 14:47 
AnswerRe: Getting this Error message....any one know y??? Pin
DaveyM6911-Mar-09 14:56
professionalDaveyM6911-Mar-09 14:56 
GeneralRe: Getting this Error message....any one know y??? Pin
S K Y11-Mar-09 15:26
S K Y11-Mar-09 15:26 
GeneralRe: Getting this Error message....any one know y??? Pin
DaveyM6911-Mar-09 15:34
professionalDaveyM6911-Mar-09 15:34 
GeneralRe: Getting this Error message....any one know y??? Pin
Christian Graus11-Mar-09 15:58
protectorChristian Graus11-Mar-09 15:58 
GeneralRe: Getting this Error message....any one know y??? Pin
S K Y11-Mar-09 18:18
S K Y11-Mar-09 18:18 
QuestionHow to use OleDbConnection or SqlCommand to read Schema and database records [modified] Pin
granthamlee11-Mar-09 14:30
granthamlee11-Mar-09 14:30 
Hello,

Can someone suggest how I can improve the code below to use just one kind of SQL connection to read both the Database table column names and the records in the table? I am using OleDb to read the column names from the table, then SqlCommand to read the records, but I would like to use only the one or the other. How can I read the DB records using OleDb please?

Can I use SqlCommand to read the column names from the table schema?
I am using Visual C# 2005 Express.
Thank you for taking the time to read this!



using System;
using System.IO;
using System.Text;
using System.Data;
using System.Collections; //For using array list
using System.Data.OleDb;
using System.Threading;
using System.Data.SqlClient;
using System.Configuration; //Used for Configuration Manager


namespace exportToCSVfile
{
    public class Program
    {
        static int Main( string[] args )
        {

            //SQL Connection - used for reading the DB table column names
            OleDbConnection connOleDB = new OleDbConnection();
            connOleDB.ConnectionString = ( the connection string );

            //SQL Connection - used for reading the DB records
            SqlConnection conn = new SqlConnection( another connection string );
            DataTable schemaTable;
            string strRow; // represents a full row

            // Used for writing the CSV file.
            string fileOut = ConfigurationManager.AppSettings["directoryPathKey"] + ConfigurationManager.AppSettings["fileCSVNameKey"];

            // Used for writing the log file.
            string fileLogFullPath = ConfigurationManager.AppSettings["directoryPathKey"] + ConfigurationManager.AppSettings["fileLogNameKey"];

            //Check the directory in the config file exists and exit if not
            if ( !Directory.Exists( ConfigurationManager.AppSettings["directoryPathKey"] ) )
            {
                Console.WriteLine (
                 "Directory \"{0}\" does not exist", ConfigurationManager.AppSettings["directoryPathKey"]);
                //Pause
                Console.ReadLine();
                return 0;
            }

 


            try
            {
                connOleDB.Open();

                /// <Summary>
                /// Connect to the database and read the table headers
                /// Be sure to use an account that has permission to list the columns in the table.
                /// <Summary>

                //Retrieve schema information about columns.
                //Restrict to just the Employees TABLE.
                schemaTable = connOleDB.GetOleDbSchemaTable( OleDbSchemaGuid.Columns,
                              new Object[] { null, null, "SomeDatabaseTable", null } );


                //List the column name from each row in the schema table.
                int theArrayBounds = schemaTable.Rows.Count;
                string[] columnNames = new string[theArrayBounds];


                for ( int i = 0; i < schemaTable.Rows.Count; i++ )
                {
                    object objColumnNames = ( schemaTable.Rows[i].ItemArray[3].ToString() );
                    columnNames[i] = objColumnNames.ToString();
                    //Console.WriteLine( schemaTable.Rows[i].ItemArray[3].ToString() );//For debugging purposes
                }

                //Explicitly close - don't wait on garbage collection.
                connOleDB.Close();
                //Console.WriteLine( "Connection Closed." );

 


                /// <Summary>
                /// Connect to the database and read the records
                /// <Summary>
                //Connects to the database, and makes the select command.
                string sqlQuery = "SELECT * FROM SomeDatabaseTable";
                SqlCommand command = new SqlCommand( sqlQuery, conn );
                conn.Open();


                // Creates a SqlDataReader instance to read data from the table.
                SqlDataReader dr = command.ExecuteReader();


                // Retrieves the schema of the table.
                DataTable dtSchema = dr.GetSchemaTable();


                // Writes the column headers.
                StreamWriter sw = new StreamWriter( fileOut, false, Encoding.Default );// Creates the CSV file as a stream, using the given encoding.
                string columnHeaderString = String.Join( ",", columnNames );//Convert an array to a comma-delimited string
                sw.WriteLine( columnHeaderString );

 

                // Reads the rows one by one from the SqlDataReader
                // transfers them to a string with the given separator character and writes it to the file.
                while ( dr.Read() )
                {
                    strRow = "";
                    for ( int i = 0; i < dr.FieldCount; i++ )
                    {
                        strRow += Convert.ToString( dr.GetValue( i ) );
                        if ( i < dr.FieldCount - 1 )
                        {
                            strRow += ",";
                        }
                    }
                    sw.WriteLine( strRow );
                }

                // Closes the text stream and the database connection.
                sw.Close();
                conn.Close();
            }
            catch ( Exception exception )
            {
                Console.WriteLine( exception );
                Thread.Sleep( 3000 );
                using ( TextWriter tw = new StreamWriter( fileLogFullPath ) )
                {
                    tw.WriteLine( DateTime.Now + "Error: " + exception.ToString() );
                }

                //Explicitly close - don't wait on garbage collection.
                connOleDB.Close();
                //Console.WriteLine( "Connection Closed." );
                // Closes the text stream and the database connection.
                conn.Close();
                return 0;
            }
            finally
            {
                //Explicitly close - don't wait on garbage collection.
                connOleDB.Close();
                //Console.WriteLine( "Connection Closed." );
                // Closes the text stream and the database connection.
                conn.Close();
            }
            
            return 1;
        }
    }
}



I have taken help from various sources for the code and I extend my most grateful thanks;
http://www.codeproject.com/KB/database/Cs_CSV_import_export.aspx[^]
I would include other references but I've lost those links during my extensive searching.

modified on Thursday, March 12, 2009 3:49 PM

QuestionSyste.OutOfMemoryException Pin
Member 461797111-Mar-09 14:23
Member 461797111-Mar-09 14:23 
AnswerRe: Syste.OutOfMemoryException [modified] Pin
Luc Pattyn11-Mar-09 14:34
sitebuilderLuc Pattyn11-Mar-09 14:34 
AnswerRe: Syste.OutOfMemoryException Pin
DaveyM6911-Mar-09 14:40
professionalDaveyM6911-Mar-09 14:40 
AnswerRe: Syste.OutOfMemoryException Pin
DaveyM6911-Mar-09 14:45
professionalDaveyM6911-Mar-09 14:45 
AnswerRe: Syste.OutOfMemoryException Pin
Member 461797111-Mar-09 14:48
Member 461797111-Mar-09 14:48 
GeneralRe: Syste.OutOfMemoryException Pin
DaveyM6911-Mar-09 14:52
professionalDaveyM6911-Mar-09 14:52 
GeneralRe: Syste.OutOfMemoryException Pin
Member 461797111-Mar-09 14:59
Member 461797111-Mar-09 14:59 
GeneralRe: Syste.OutOfMemoryException Pin
DaveyM6911-Mar-09 15:26
professionalDaveyM6911-Mar-09 15:26 
GeneralRe: Syste.OutOfMemoryException Pin
Luc Pattyn11-Mar-09 15:46
sitebuilderLuc Pattyn11-Mar-09 15:46 
GeneralRe: Syste.OutOfMemoryException Pin
DaveyM6911-Mar-09 15:56
professionalDaveyM6911-Mar-09 15:56 
GeneralRe: Syste.OutOfMemoryException Pin
Luc Pattyn11-Mar-09 16:06
sitebuilderLuc Pattyn11-Mar-09 16:06 
GeneralRe: Syste.OutOfMemoryException Pin
DaveyM6911-Mar-09 23:03
professionalDaveyM6911-Mar-09 23:03 
GeneralRe: Syste.OutOfMemoryException Pin
Member 461797111-Mar-09 15:06
Member 461797111-Mar-09 15:06 
GeneralRe: Syste.OutOfMemoryException Pin
Luc Pattyn11-Mar-09 15:13
sitebuilderLuc Pattyn11-Mar-09 15:13 
GeneralRe: Syste.OutOfMemoryException Pin
Member 461797111-Mar-09 15:16
Member 461797111-Mar-09 15:16 
GeneralRe: Syste.OutOfMemoryException [modified] Pin
Luc Pattyn11-Mar-09 15:49
sitebuilderLuc Pattyn11-Mar-09 15:49 
GeneralRe: Syste.OutOfMemoryException Pin
Member 461797111-Mar-09 16:53
Member 461797111-Mar-09 16:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.