0

I have list of values:

string[] DataValues

now I want to put all the value into insert:

string myInsert = "Insert into table1(col1, col2, col3....col4) values (DataValues[0],DataValues [1], DataValues[2]....)

It's posssible to use somehow foreach?

4
  • @MohammedNoureldin Doesnt even make that huge difference in code, since you can easily convert the code with a for loop to code with a foreach loop, or the other way round. Commented Dec 18, 2017 at 13:02
  • foreach (string s in DataValues) { //insert s into database; } Commented Dec 18, 2017 at 13:03
  • Why not just use the String.Join method Commented Dec 18, 2017 at 13:07
  • 3
    If you are creating SQL like this, you are going to open yourself up to SQL injection and bugs. Please be very careful... Commented Dec 18, 2017 at 13:09

1 Answer 1

2

To get exactly what your want you can format your DataValues like so:

var paramList = string.Join(",",DataValues.Select(x=>string.Format("'{0}'",x)).ToArray()

I presume you have the same for columns list.

BUT DO NOT DO THAT

this will make your code prone to sql injection you should declare parameter for each value and use it via parameter.

var parameters = string.Join(",",DataValues.Select((x,i)=>"@param"+i));
var myInsert = string.Format("Insert into table1({0}) values ({1})", columns, parameters);

using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
    for(var i=0; i< DataValues.Length ; i++)
    {
       var param = cmd.Parameters.Add("@param"+i,  SqlDbType.NVarChar, DataValues[i].Length);
       param.Value = DataValues[i];
    }
    command.ExecuteNonQuery();
}
Sign up to request clarification or add additional context in comments.

2 Comments

@DavidG yes ok, fixed.
thx Rafal, the insert command will be saved inside file.sql, so "myInsert" I can easly write to file

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.