Click here to Skip to main content
Click here to Skip to main content

Importing CSV Data and saving it in database

By , 25 Aug 2005
 

Introduction

Nowadays it is common in applications to have the functionality of reading the CSV data. My current project needed one. Even after searching for long, I could not get one which could satisfy my requirements. But after doing considerable amount of study, I came up with the following tool. CSV files stand for Comma Separated Value files. They are common text files with comma delimited values. Though the default delimiter is comma (,), we can specify other characters as delimiters like the semi-colon (;), colon (:), asterisk (*). But you cannot specify double quotes (") as a delimiter. I have used Microsoft Text Drivers for reading the CSV data. You have to use ODBC connection for accessing the CSV data. You can either create a DSN or use the connection string. If you create a DSN, the schema.ini file gets created automatically in the folder where all your CSV files reside. But if you use connection string, you have to create schema.ini file on your own. We are going to see the latter approach.

Schema.ini File (Text File Driver)

When the Text driver is used, the format of the text file is determined by using a schema information file. The schema information file, which is always named schema.ini and always kept in the same directory as the text data source, provides the IISAM with information about the general format of the file, the column name and data type information, and a number of other data characteristics.

Using the demo application

For successfully running the application you need Test.csv file and a database with a table having three columns. But all this is provided in the demo application. So you need not worry. Follow these steps to run the demo application:

  1. First run DBI.exe application.
  2. The screen shown below will appear.
  3. Fill the required details and click the button "Install".
  4. Make sure that a folder named "Test" is created in "D:" drive with the Test.csv file in it.
  5. Now run our main application i.e. FinalCSVReader.exe.
  6. Keep the default folder and file path as it is.
  7. First click "Import CSV data" to import the CSV data.
  8. Now click "Save", to save the data in the database.

Using the source code

Some important parts of the code are discussed below

Create schema.ini

This is a function writeSchema(). It creates the schema.ini file dynamically.

/*Schema.ini File (Text File Driver)

 When the Text driver is used, the format of the
 text file is determined by using a schema information
 file. The schema information file, which is always named
 Schema.ini and always kept in the same directory as the
 text data source, provides the IISAM with information
 about the general format of the file, the column name
 and data type information, and a number of other data 
 characteristics*/

private void writeSchema()
{
 try    
    {
        FileStream fsOutput = 
             new FileStream (txtCSVFolderPath.Text+"\\schema.ini", 
                                 FileMode.Create, FileAccess.Write);
        StreamWriter srOutput = new StreamWriter (fsOutput);
        string s1, s2, s3,s4,s5;
        s1="["+strCSVFile+"]";
        s2="ColNameHeader="+bolColName.ToString ();
        s3="Format="+strFormat;
        s4="MaxScanRows=25";
        s5="CharacterSet=OEM";
        srOutput.WriteLine(s1.ToString()+'\n'+s2.ToString()+
                                    '\n'+s3.ToString()+'\n'+
                                    s4.ToString()+'\n'+s5.ToString());
        srOutput.Close ();
        fsOutput.Close ();                    
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
    }

Function for importing the CSV Data

This function ConnectCSV (string filetable) takes the .csv file name as argument and returns the dataset containing the imported data.

public DataSet ConnectCSV (string filetable)
{
  DataSet ds = new DataSet ();
  try
   {        
       /* You can get connected to driver either by using
       DSN or connection string. Create a connection string
       as below, if you want to use DSN less connection.
       The DBQ attribute sets the path of directory which 
       contains CSV files*/

       string strConnString=
             "Driver={Microsoft Text Driver (*.txt;*.csv)};
             Dbq="+txtCSVFolderPath.Text.Trim()+";
             Extensions=asc,csv,tab,txt;
             Persist Security Info=False";

       string sql_select;                                
       System.Data.Odbc.OdbcConnection conn;        
        
       //Create connection to CSV file
       conn = new System.Data.Odbc.OdbcConnection(
                                    strConnString.Trim ());

       // For creating a connection using DSN, use following line
       //conn = new System.Data.Odbc.OdbcConnection(DSN="MyDSN");
    
       //Open the connection 
       conn.Open ();
       //Fetch records from CSV
       sql_select="select * from ["+ filetable +"]";
                
       obj_oledb_da=new System.Data.Odbc.OdbcDataAdapter(
                                                sql_select,conn);
       //Fill dataset with the records from CSV file
       obj_oledb_da.Fill(ds,"Stocks");
                
       //Set the datagrid properties
                
       dGridCSVdata.DataSource=ds;
       dGridCSVdata.DataMember="Stocks";
       //Close Connection to CSV file
       conn.Close ();                
   }
   catch (Exception e) //Error
   {
       MessageBox.Show (e.Message);
   }
   return ds;
}

Code for inserting the data

This is a code written in the button's click event btnUpload_Click. This actually inserts the data in the database.

private void btnUpload_Click(object sender, 
                                System.EventArgs e)
{
 try
  {
    // Create an SQL Connection
    // You can use actual connection 
    // string instead of ReadConFile()

    SqlConnection  con1=
         new SqlConnection(ReadConFile().Trim());
    SqlCommand cmd = new SqlCommand();
    SqlCommand cmd1 = new SqlCommand();

    // Create Dataset                    
    DataSet da = new DataSet();

    /* To actually fill the dataset,
    Call the function ImportCSV and   assign 
    the returned dataset to new dataset as below */

    da=this.ConnectCSV(strCSVFile);    

    /* Now we will collect data from data table
    and insert it into database one by one.
    Initially there will be no data in database 
    so we will insert data in first two columns 
    and after that we will update data in same row
    for remaining columns. The logic is simple.
    'i' represents rows while 'j' represents columns*/

    cmd.Connection=con1;
    cmd.CommandType=CommandType.Text;
    cmd1.Connection=con1;
    cmd1.CommandType=CommandType.Text;
                    
    con1.Open();
    for(int i=0;i<=da.Tables["Stocks"].Rows.Count-1;i++)
    {                        
      for(int j=1;j<=da.Tables["Stocks"].Columns.Count-1;j++)
      {
        cmd.CommandText= 
          "Insert  into Test(srno,
             "+da.Tables["Stocks"].Columns[0].ColumnName.Trim()+")
          values("+(i+1)+",
             '"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(0)+"')";
        
        /* For UPDATE statement, in where clause you
        need some unique row identifier. We are using 
        ‘srno’ in WHERE clause. */

        cmd1.CommandText=
          "Update Test set "
              +da.Tables["Stocks"].Columns[j].ColumnName.Trim()+"
              = '"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(j)+
          "' where srno ="+(i+1);                            
        cmd.ExecuteNonQuery();
        cmd1.ExecuteNonQuery();                            
      }
    }
    con1.Close();
  }
  catch(Exception ex)
  {
      MessageBox.Show(ex.Message);
  }
  finally
  {
      btnUpload.Enabled=false;
  }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Mukund Pujari
India India
Member
*****

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionDBI.exe issuememberDawar199 Jan '13 - 22:14 
DBI.exe is not opening in Win 7..not getting the relevant issue Sigh | :sigh:
GeneralMy vote of 1memberSyed Javed14 Feb '12 - 19:58 
Buggy, does not work
AnswerRe: My vote of 1memberjohn_172619 Dec '12 - 6:26 
What error are you getting? When I tried to run it, I got this error:
 
ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
 
The problem was that the project was set to "Any CPU" on an x64 machine. So when I changed the Build->Platform target to x86, it ran fine with no problem.
QuestionExcelmemberMember 83651881 Nov '11 - 2:02 
Hi
I just want to know how to import data from excel to database in sql using asp.net.....
Suppose my excel file has 30 rows(can be extended).....first i want to fetch data from 6th row(till 10 columns) onward till it finds a blank row.....and then from next row containing data.....so that data will be saved in database from 11 column
AnswerRe: ExcelmemberJamesHoward97213 Dec '11 - 21:57 
Hello,
 
you can easily export Excel file (XLS or XLSX) to database in Excel ASP.NET environment with this Excel C# / VB.NET component.
 
Here is a sample Excel C# code how to export Excel to DataTable and then use SqlDataAdapter to update the database:
 
var excelFile = new ExcelFile();
 
excelFile.LoadXls("MyFile.xls");
 
var worksheet = excelFile.Worksheets[0];
 
// Extract all used cells to DataTable, automatically determine column types based on cell content, skip empty rows and use first row as column headers.
var dataTable = worksheet.CreateDataTable(worksheet.GetUsedCellRange(true), ColumnTypeResolution.Auto, ExtractDataOptions.SkipEmptyRows, true);
 
// Update the SQL database.
sqlDataAdapter.Update(dataTable);

QuestionHow can convert .CVS to Text files with appending 2 rowsmembersrid812 Oct '11 - 0:46 
hi
 
I just saw the code and the project , i would like to know how to Extract or import data from .CVS to text file , and i would like to add 2 rows like sl no ,and catagory
 

Example of cvs file will be like
date Expect 1 Expect2 Expect3 Expect4
 

these are numbers in 4 rows and date with it
 
Date Expect1 Expect2 Expect3 Expect4
10/11/2011 0 1 2 4
 
this will be the .cvs file
 
and i want it to be like
 
SLno category Date Expect1 Expect2 Expect3 Expect4
1 Student 10/11/2011 0 1 2 4
 
So can you please help me in this
 

the form out look is ok
just take the .cvs file add Slno and category and dump it to txt file
 

Regards
Sridhar
QuestionZero in front of numeric had been remove offmemberPrasertHong6 Oct '11 - 17:59 
If CSV file contain cell that represent serial number, so this number will have zero in front of the set of numeric, after import CSV data, the zero in front of numeric will be remove and datagrid will set this cell as numeric instead of text cell as design. How to solve this problem?
QuestionDBI.exememberFred C Edwards6 Oct '11 - 6:16 
I tried to run the DBI.exe and it won't work! What is the format of the file it creates so I can manually build it?
QuestionNice Article & CodememberEd Gadziemski17 Jul '11 - 20:54 
Thank you for writing this article and sharing your code. One small suggestion is to set MaxScanLines to at least 64 so that datatyping is more accurate. Other than that, I think this is a useful application and I especially like your screen layout. It is simple and functional, and what more can one ask?
GeneralMy vote of 2memberVikasumit6 May '11 - 7:52 
Not a very optimize way of doing the job.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 25 Aug 2005
Article Copyright 2005 by Mukund Pujari
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid