I am writing a simple c# application wherein I read from a file a line, split it, and insert the corresponding tokens into an access database after suitable conversion. I am using a stream reader to read the input file line by line. Here's a snippet of my code.
using(reader = Streamreader(filepath)
{
while((line = reader.readline()) != null)
{
string[] tokens = line.split('\t');
mycommand.commandtext = "INSERT INTO table_name (name, property) VALUES (@xname, @xproperty)";
mycommand.parameters.addwithvalue("@xname", tokens[0]);
mycommand.parameters.addwithvalue("@xproperty", float.parse(tokens[1]);
mycommand.executenonquery();
}
}
The problem is that if the input file contains 6 distinct lines, then only the values associated with the first line are duplicated 6 times into my database. What am I doing wrong?
You can't replace the parameters in a loop because OleDBCommand does not support named parameters. The parameter replacement is made in the order you add Parameters, therefore you have to create a new command every run, because the 2nd loop run you add a 3rd and 4th parameter (while you only use two).