Reputation: 1
I want to import data from a .txt
file to the database. The problem is, I don't need the first row and column of the .txt
file. How can I skip them? The data is separated by ";".
Following is the code I tried -
private void txtinsert ()
{
string constr = (@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\szabo\Desktop\Programozas\C#\Etelek (2016)\Start\Start\GOOD_FOOD.mdf; Integrated Security = True; Connect Timeout = 30");
SqlConnection con = new SqlConnection(constr);
StreamReader sr = new StreamReader(Application.StartupPath + @"\..\..\meniu.txt");
string sir;
char[] split = {';'};
con.Open();
SqlCommand cmd = new SqlCommand();
while ((sir = sr.ReadLine()) != null)
{
string[] siruri = sir.Split(split);
cmd = new SqlCommand("INSERT INTO Meniu (id_produs) VALUES (@id_produs)", con);
cmd.Parameters.AddWithValue("@id_produs", siruri[0].Trim());
cmd.ExecuteNonQuery();
}
}
Upvotes: 0
Views: 51
Reputation: 49395
You could use a variable to indicate which rows you don't want, and you know how many rows where processed
private void txtinsert ()
{
string constr = (@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\szabo\Desktop\Programozas\C#\Etelek (2016)\Start\Start\GOOD_FOOD.mdf; Integrated Security = True; Connect Timeout = 30");
SqlConnection con = new SqlConnection(constr);
StreamReader sr = new StreamReader(Application.StartupPath + @"\..\..\meniu.txt");
string sir;
char[] split = {';'};
int RowNum = 0;
con.Open();
SqlCommand cmd = new SqlCommand();
while ((sir = sr.ReadLine()) != null)
{
if (RowNum > 0) {
string[] siruri = sir.Split(split);
cmd = new SqlCommand("INSERT INTO Meniu (id_produs) VALUES (@id_produs)", con);
cmd.Parameters.AddWithValue("@id_produs", siruri[0].Trim());
cmd.ExecuteNonQuery();
}
RowNum +=1;
}
}
Upvotes: 1
Reputation: 48407
You could read the first line outside of the while
loop.
sir = sr.ReadLine();
while ((sir = sr.ReadLine()) != null)
{
string[] siruri = sir.Split(split);
cmd = new SqlCommand("INSERT INTO Meniu (id_produs) VALUES (@id_produs)", con);
cmd.Parameters.AddWithValue("@id_produs", siruri[0].Trim());
cmd.ExecuteNonQuery();
}
Upvotes: 0