So, want to make a multi-row insert query, and I need to replace the keys with the values inside a loop where I have the values.
It was working by hardcoding the values into the query string, but I need to do it by using the "cmd.Parameters.AddValue()
or cmd.Parameters.AddWithValue()
" as I need to prevent SQL Injection.
So, my code is something like this:
string query = "insert into dbo.Foo (column1, column2, column3) values ";
SqlCommand cmd
foreach (line in rowsArray) {
cmd.Parameters.Clear();
cmd = new SqlCommand(query, cnn); //So, the problem is this override
query += "(@key1, @key2, @key3), ";
cmd.Parameters.AddWithValue("@key1", line.value1);
cmd.Parameters.AddWithValue("@key2", line.value2);
cmd.Parameters.AddWithValue("@key3", line.value3);
}
query = query.Substring(0, query.Length-2); //Last comma
cmd.ExecuteNonQuery();
cnn.Close();
I want to ExecuteNonQuery();
outside the loop, to make just one insert.
Any ideas?
I thought about making a loop where I add the keys in the string with a identifier and then replacing all of them iterating another loop with the same id's, but I don't see that very efficient or a good practice.
1, 2, 3
repeating. – InvariantExecuteNonQuery
calls, and then commit the transaction at the end. There may well be better ways, but I'd at least expect that to work. Otherwise, you'd need to create multiple insert statements in your SQL, with uniquely-named parameters. – TimeousSqlBulkCopy
for bulk insert, use this link: https://mcmap.net/q/29000/-sqlbulkcopy-from-a-list-lt-gt – HunnishVALUES
clause, and statements like these (with many different parameter counts) pollute the plan cache. Generally this approach is not worth it; use either a multi-statement transaction, a table-valued parameter or theSqlBulkCopy
class. (And don't useAddWithValue
). – Taishataisho