I have the following code for reading from a file and populating my database. Everything works fine except that all records are inserted twice.
OleDbCommand c = new OleDbCommand();
c.Connection = GetConnection();
c.CommandText =
@"CREATE TABLE patients (
patientid AUTOINCREMENT PRIMARY KEY,
firstlastname CHAR(50),
birthdate CHAR(50),
birthplace CHAR(50),
gender CHAR(1),
bloodtype CHAR(50),
telnum CHAR(50),
address CHAR(255)
)";
c.ExecuteNonQuery();
string info = "";
string name = "";
string date = "";
string place = "";
string blood = "";
string num = "";
string address = "";
//Read from file and insert values to patient table
StreamReader myReader = new StreamReader("myPath/patient.txt");
while (true)
{
info = myReader.ReadLine();
if (info == null) break;
if (info.Trim() != String.Empty)
{
string[] words = info.Split(',');
if (words.Length == 6)
{
name = words[0].Trim();
date = words[1].Trim();
place = words[2];
blood = words[3];
num = words[4];
address = words[5];
}
}
string cmdText = "INSERT INTO patients (" +
"firstlastname, birthdate, birthplace, bloodtype, telnum, address) " +
"VALUES (?,?,?,?,?,?)";
using (OleDbConnection cn = GetConnection())
{
using (OleDbCommand cmd = new OleDbCommand(cmdText, cn))
{
cmd.Parameters.AddWithValue("name", name);
cmd.Parameters.AddWithValue("date", date);
cmd.Parameters.AddWithValue("place", place);
cmd.Parameters.AddWithValue("blood", blood);
cmd.Parameters.AddWithValue("num", num);
cmd.Parameters.AddWithValue("address", address);
cmd.ExecuteNonQuery();
}
}
}
I noticed that the line
if (info.Trim() != String.Empty)
returns “false” every other time so records are inserted twice but dont know how to fix this.
How can i eliminate these duplicates?.
Thanks
EDIT: File contents are as such showing name, date, city, blood type, mobile num and address:
Mehtap Selim, 11/06/1985, Kyrenia, FBRh+, 05617584509, Yasemin St. No:48 Edremit Kyrenia KKTC
What it looks like is that your code structure is still allowing a write to your database even if the conditional statement is false and since the data is still in your variables from the previous write it writes them again. Try enclosing the Database writing into the same conditional. As for why it is coming up false every other time we would need to see the contents of your file.
i.e.