Click here to Skip to main content
15,505,080 members
Articles / Database Development / SQL Server
Posted 25 Aug 2005


211 bookmarked

Importing CSV Data and saving it in database

Rate me:
Please Sign up or sign in to vote.
4.45/5 (57 votes)
25 Aug 20052 min read
This article shows how to import CSV data and store it in database.

Image 1


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.

Image 2

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 

private void writeSchema()
        FileStream fsOutput = 
             new FileStream (txtCSVFolderPath.Text+"\\schema.ini", 
                                 FileMode.Create, FileAccess.Write);
        StreamWriter srOutput = new StreamWriter (fsOutput);
        string s1, s2, s3,s4,s5;
        s2="ColNameHeader="+bolColName.ToString ();
        srOutput.Close ();
        fsOutput.Close ();                    
    catch (Exception ex)

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 ();
       /* 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)};
             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(
       //Fill dataset with the records from CSV file
       //Set the datagrid properties
       //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)
    // 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 */


    /* 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*/

    for(int i=0;i<=da.Tables["Stocks"].Rows.Count-1;i++)
      for(int j=1;j<=da.Tables["Stocks"].Columns.Count-1;j++)
          "Insert  into Test(srno,
        /* For UPDATE statement, in where clause you
        need some unique row identifier. We are using 
        ‘srno’ in WHERE clause. */

          "Update Test set "
              = '"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(j)+
          "' where srno ="+(i+1);                            
  catch(Exception ex)


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

Written By
India India

Comments and Discussions

Questionquestion Pin
Member 1154683523-Mar-15 3:04
Member 1154683523-Mar-15 3:04 
QuestionDBI.exe issue Pin
Dawar199-Jan-13 23:14
Dawar199-Jan-13 23:14 
GeneralMy vote of 1 Pin
Syed Javed14-Feb-12 20:58
Syed Javed14-Feb-12 20:58 
AnswerRe: My vote of 1 Pin
Roger C Moore19-Dec-12 7:26
Roger C Moore19-Dec-12 7:26 
QuestionExcel Pin
Member 83651881-Nov-11 3:02
Member 83651881-Nov-11 3:02 
AnswerRe: Excel Pin
JamesHoward97213-Dec-11 22:57
JamesHoward97213-Dec-11 22:57 
QuestionHow can convert .CVS to Text files with appending 2 rows Pin
srid812-Oct-11 1:46
srid812-Oct-11 1:46 
AnswerRe: How can convert .CVS to Text files with appending 2 rows Pin
Member 124464206-Jul-18 2:36
professionalMember 124464206-Jul-18 2:36 
QuestionZero in front of numeric had been remove off Pin
PrasertHong6-Oct-11 18:59
PrasertHong6-Oct-11 18:59 
QuestionDBI.exe Pin
Fred C Edwards6-Oct-11 7:16
Fred C Edwards6-Oct-11 7:16 
QuestionNice Article & Code Pin
Ed Gadziemski17-Jul-11 21:54
professionalEd Gadziemski17-Jul-11 21:54 
GeneralMy vote of 2 Pin
Vikasumit6-May-11 8:52
professionalVikasumit6-May-11 8:52 
General? about "srno" Pin
bobk54415-Apr-11 9:56
bobk54415-Apr-11 9:56 
GeneralRe: ? about "srno" Pin
bobk54417-Apr-11 12:40
bobk54417-Apr-11 12:40 
GeneralMy vote of 3 Pin
Member 159022329-Oct-10 3:17
Member 159022329-Oct-10 3:17 working sample Pin
Fl@ppie11-Oct-10 3:40
Fl@ppie11-Oct-10 3:40 
GeneralMy vote of 3 Pin
kvicky9-Aug-10 20:56
kvicky9-Aug-10 20:56 
GeneralMy vote of 5 Pin
programmerjiwa20-Jul-10 17:16
programmerjiwa20-Jul-10 17:16 
GeneralPlz update project to the latest version of VS.NET 2008 Pin
programmerjiwa8-Jul-10 18:28
programmerjiwa8-Jul-10 18:28 
Questionimport csv without using datagrid Pin
rainbowemo11-May-10 6:44
rainbowemo11-May-10 6:44 
Questionwhat to put in username at demo file Pin
Jaedah27-Feb-10 9:09
Jaedah27-Feb-10 9:09 
QuestionHow to import txt / csv file in unicode/utf8 format? Pin
Leo Kwong18-Nov-09 18:23
Leo Kwong18-Nov-09 18:23 
GeneralDatabase description Pin
Jesper Bonander15-Jun-09 4:58
Jesper Bonander15-Jun-09 4:58 
QuestionColumns name problem Pin
Rupeshivani14-Jun-09 22:53
Rupeshivani14-Jun-09 22:53 
QuestionHow to import one CSV with more than 256 columns? Pin
wind214-Apr-09 22:53
wind214-Apr-09 22: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.