If I guess what you're trying to do, you want to do this:
You want to add the ONE parameter and change the VALUE value of the parameter in the loop.
var db2Cmd = new OdbcCommand("INSERT INTO presnlats (LAT) VALUES (@Lat)", db2Conn); db2Cmd.Parameters.AddWithValue("@Lat", 0); for (int j = 0; j < reader.FieldCount; ++j) { db2Cmd.Parameters["@Lat"].Value = reader[j]; Console.Out.WriteLine(db2Cmd.ExecuteNonQuery()); }
Added
You only have one placeholder (@Lat) for your parameter in the command, so you should only add one parameter. Your code adds a new parameter for each object to the reader. None of these parameters will be called "@Lat" unless your reader returns @Lat.
I'm still pretty sure that you need one parameter (@Lat) and you need to change the parameter value in a loop.
Explaining the syntax for using parameterized queries, consider this statement:
cmd.CommandText = "Insert into the face (name FirstName, LastName) values ββ(@fName, @lName)
In the above description, @fName and @lName are NOT parameters. They are placeholders for parameters.
Then you need to explicitly add the parameters using the following rules:
- Parameters must be named exactly like placeholders
- The paramaters must be added in the correct order.
Thus, a more complete example would be
cmd.CommandText = "Insert into the face (name FirstName, LastName) values ββ(@fName, @lName)
cmd.Parameters.AddWithValue ("@fName", "David"); // This line in this context says: "Repeat the palceholder parameter from the previous line with this actual parameter. cmd.Parameters.AddWithValue (" @lName "," Stratton "); // in the same way, it replaces the @lname placeholder.
Then, if I have a datareader that has a bunch of names, I can reassign VALUE from the reader to VALUE of this parameter.
while (myReader.Read ()) {cmd.Parameters ["@fName ']. Value = myReader.GetString (" FirstNameField "); cmd.Parameters [" @lName']. Value = myReader.GetString ("LastNameField"); cmd.ExecuteNonQuery ();
}