我有以下代碼用於從文件讀取並填充我的數據庫。一切工作正常,但所有記錄都插入兩次。從數據庫中刪除重複項
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();
}
}
}
我注意到,行 if (info.Trim() != String.Empty)
返回「假」,所以記錄插入兩次,但不知道如何解決這個問題每個其他時間。
我該如何消除這些重複? 感謝
編輯:文件內容顯示等名稱,日期,城市,血型,移動NUM和地址:
Mehtap塞利姆,1985年11月6日,凱里尼亞,FBRh +,05617584509,Yasemin聖編號:48 Edremit Kyrenia KKTC
把你的INSERT命令中,如果代碼塊 – MethodMan