Reading Data from .csv File and Writing into SQL

Introduction

This is a simple programs written in C# which reads data of records from a .csv File, And write these records to a SQL Database accordingly. The CSV (“Comma Separated Value”) file format is often used to exchange data between disparate applications.

Tools: 

1. Visual Studio 2010
2. Microsoft SQL 2008
3. Language: C#

 Background

Sometimes we need to store records while we have to use very limited memory. In that case a .csv file is used to store records and information or in other words called Flat File Database. Its less size feature is very useful when we are transferring this database over network via streams. The record is stored in .csv files as One Record per line and is separated by a specific delimiter (which is “,” in .csv files) to differentiate between columns.

Using the Code

Let’s move through the code

Untitled1

This is a simple piece of code which fetch the records from .csv File separate them on the base of Delimiter(which is “,” in csv files) and the place them in the Data table object which is “dt” using Microsoft Jet OLEDB Adapter.

Now we have all the records of the .csv File into data table each at its respective column and row. It’s time to write these records to Microsoft SQL Server. We already have a Table there  with all the column names.

The attribute FMT =Delimited in the connection string defines the delimiter, the program will automatically identify that it is comma delimited or tab delimited and will separate the record accordingly.

File name from where we want records “Gan_Advertisers.csv”

Untitled2

 

Now we have to write the data which is present in our data table into the SQL Server database, and data is written into the SQL Database until all the rows successfully transferred to the SQL database.

Untitled3

After that data is written in SQL.

Now we have read data from a csv file and wrote it into SQL database.