I’ve got a DataTable which has a number of records.
I’ve tried the following code for iterating through the DataTable and inserting into the database, but I am receiving an error message saying that the parameters have not been declared:
using (SqlCommand command = new SqlCommand(("My insert statement"), connection))
{
SqlParameter param1 = new SqlParameter();
SqlParameter param2 = new SqlParameter();
param1.ParameterName = "@ProductID";
param2.ParameterName = "@ID";
foreach (DataRow row in table.Rows)
{
param1.Value = row[0].ToString();
param2.Value = row[1].ToString();
command.ExecuteNonQuery();
}
}
Any ideas? Please do not suggest stored procedures – I’d like to do this through this method or something similar.
You need to add your parameters to the command.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
Caution though
The way you have your code if you put the add in the foreach your first execute will work and then the next will fail with an error message stating that you have a variable named @ProductID / @ID already.
You need to clear the parameters each time.
See this for an example.