0

i write an application that creates an excel file with OleDb, the problem is that when the program runs a foreach loop it writes always the same data in the row, not the different value of the object in the loop.

The code is:

foreach(var user in userList)
{
   cmd.CommandText = @"INSERT INTO [User](Id , Name , Code, Username, Location, 
                  CompanyCode, MyDate, Email, MyNote)
                  VALUES(@Id, @Name, @Code, @Username, @Location)";


  cmd.Parameters.AddRange(new OleDbParameter[]
  {
    new OleDbParameter{ ParameterName = "@Id", Value = user.ID},
    new OleDbParameter{ ParameterName = "@Name", Value = user.NAME  ?? string.Empty},
    new OleDbParameter{ ParameterName = "@Code", Value = user.CODE ??  string.Empty},
    new OleDbParameter{ ParameterName = "@Username", Value = user.USERNAME ?? string.Empty},
    new OleDbParameter{ ParameterName = "@Location", Value = user.LOCATION ?? string.Empty},

  });

cmd.ExecuteNonQuery();
}

I have 12 user but the excel file has 12 rows with the same user. Example:

ExcelRow   ID NAME CODE USERNAME LOCATION
  1        1  Fra   15    Fra       NY
  2        1  FRA   15    Fra       NY
  3        1  FRA   15    Fra       NY
  4        1  FRA   15    Fra       NY
  5        ....... 

Instead if i write normal query like:

cmd.CommandText = @"INSERT INTO [User](Id , Name , Code, Username, Location, CompanyCode, MyDate, Email, MyNote) VALUES(" + company.ID + ", '" + company.NAME + "', '" + company.CODE + "', '" + company.USERNAME + "', '" + company.CODE_LOCATION + "')";

It works and write 12 different user in the file. How can i solve this problem?? Thank you and sorry for my bad english.

1
  • In your parameters example you use object variable user where as on your concatenate string query you use variable company. Commented Jan 31, 2017 at 14:44

2 Answers 2

4

Add this

cmd.Parameters.Clear();

before

cmd.Parameters.AddRange(new OleDbParameter[]
Sign up to request clarification or add additional context in comments.

Comments

1

You are adding a new range of parameter to an object that already has a set of parameters. The query is using only the first set, overriding the other ones you added after that.

You need to clear the parameters before each Loop.

Use something like:

cmd.Parameters.Clear();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.