简体   繁体   中英

Add values to a Sql Database from a .txt file, skipping the first line

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();
    }    
}

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;
    }    
}

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();

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM