C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » SQL »

Import .csv to SQL database


Posted Date: 15 Jul 2009    Resource Type: Code Snippets    Category: SQL
Author: VidhyaMember Level: Silver    
Rating: 1 out of 5Points: 5



Import .csv to SQL database :

This code will import the data from the comma separated file into an SQL table using Datatables and streamreader.


DataTable dt = new DataTable();
string line = null;
int i = 0;

using (StreamReader sr = File.OpenText(@"d:\Test.csv"))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(',');
if (data.Length > 0)
{
if (i == 0)
{
foreach (object item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
dt.Rows.Add(row);
}
}
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();

SqlBulkCopy s = new SqlBulkCopy(con);
s.DestinationTableName = "Test3";
s.WriteToServer(dt);
s.Close();
con.Close();



Responses

Author: VMRK    27 Jul 2009Member Level: Silver   Points : 0
Its really nice


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
SQL  .  CSV  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Using of While Loop In Stored Procedure.
Previous Resource: Demonstration of SQL commands
Return to Discussion Resource Index
Post New Resource
Category: SQL


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use