I’ve written some basic code to parse a CSV file and input the data into a database at runtime. Variations of this code (for different delimiters and columns) have been working fine for numerous csv files, however for some reason now this code is giving me an error for a 2-column file.
using (StreamReader reader = new StreamReader(@"C:\Rawdata\Salesman.csv"))
{
string line;
StringBuilder query = new StringBuilder();
while (!reader.EndOfStream)
{
line = reader.ReadLine();
StringBuilder segment = new StringBuilder();
for (int i = 0, segno = 0; i < line.Length; i++)
{
if (line[i] != '\t')
{
segment.Append(line[i]);
}
else
{
switch (segno)
{
case 0:
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@code", segment.ToString());
break;
case 1:
cmd.Parameters.AddWithValue("@name", segment.ToString());
break;
default:
break;
}
segno++;
segment.Clear();
}
}
delCmd = "INSERT INTO sales_codes (code, name) VALUES (@code, @name)";
cmd.CommandText = delCmd;
cmd.ExecuteNonQuery();
query.Clear();
}
}
The exception being thrown is:
SqlCeException - A parameter is missing. [ Parameter ordinal = 1 ]
I’ve double and triple checked everything from the file, the code to the table schema and all looks well. What am I missing?
As it is now, your code will only add parameters when a tab (
\t) is found. If each line doesn’t end with a tab, the second parameter will not be added. This could be your problem.