c# import data from text file into sql databse line by line

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Hi
I need to import the data from a text file into a specific SQL table and im having a hard time with the command. Any help is appricated.
So I do have a text file with 2 columns separated by a space. These two columns store numbers in double form. Below is what I have now for the code and it has a few errors when compiling


<div style="color:Black;background-color:White; <pre>
<span style="color:Blue; public <span style="color:Blue; static <span style="color:Blue; void Main(<span style="color:Blue; string[] args)
{

SqlConnection thisConnection = <span style="color:Blue; new SqlConnection(<span style="color:#A31515; "Server=localhost;Port=5432;User Id=postgres;Password=a;Database=Test;");
SqlCommand nonqueryCommand = thisConnection.CreateCommand();

<span style="color:Green; // StreamReader objReader = new StreamReader("C:\Users\account\Documents\testFile.txt");

<span style="color:Blue; string[] importFile = Directory.GetFiles(<span style="color:#A31515; "C:\Users\account\Documents\testFile.txt");

<span style="color:Blue; try
{
thisConnection.Open();

nonqueryCommand.CommandText = <span style="color:#A31515; "CREATE TABLE TestTable (Time timestamp, num1 decimal (4,2), num2 decimal(4,2))";

nonqueryCommand.ExecuteNonQuery();

nonqueryCommand.CommandText = <span style="color:#A31515; "INSERT INTO TestTable VALUES (@num1, @num2)";

nonqueryCommand.Parameters.Add(<span style="color:#A31515; "@num1");
nonqueryCommand.Parameters.Add(<span style="color:#A31515; "@num2");


<span style="color:Blue; string[] allLines = File.ReadAllLines(importFile);
{
<span style="color:Blue; for(<span style="color:Blue; int i=1; i<allLines.Length; i++)
{
<span style="color:Blue; string[] items = allLines.Split(<span style="color:Blue; new <span style="color:Blue; char[] { <span style="color:#A31515; });
nonqueryCommand.Parameters[<span style="color:#A31515; "@num1"].Value = items[0];
nonqueryCommand.Parameters[<span style="color:#A31515; "@num2"].Value = items[1];
nonqueryCommand.ExecuteNonQuery();
}
}
}

<span style="color:Blue; finally
{
thisConnection.Close();
}
}


[/code]
<br/>
<br/>





View the full article
 
Back
Top