C# 从数据库中消除重复项
我有以下代码用于读取文件和填充数据库。除了所有记录都插入两次之外,一切都正常C# 从数据库中消除重复项,c#,ms-access,oledb,C#,Ms Access,Oledb,我有以下代码用于读取文件和填充数据库。除了所有记录都插入两次之外,一切都正常 OleDbCommand c = new OleDbCommand(); c.Connection = GetConnection(); c.CommandText = @"CREATE TABLE patients ( patientid AUTOINCREMENT PRIMARY KEY, firstlastname CHAR(50), birthdate C
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)
每隔一次返回“false”,因此记录会插入两次,但不知道如何修复此问题
如何消除这些重复项?。
谢谢
编辑:文件内容包括姓名、日期、城市、血型、手机号码和地址:
Mehtap Selim,1985年6月11日,Kyrenia,FBRh+,05617584509,Yasemin St.No:48 Edremit Kyrenia KKTC看起来,您的代码结构仍然允许写入数据库,即使条件语句为false,并且由于数据仍然位于上一次写入的变量中,因此会再次写入它们。尝试将数据库写入同一条件中。至于为什么每隔一段时间就会出现错误,我们需要查看您文件的内容 i、 e
如果代码BlockYes,将insert命令放在其中,我还将更改一些其他内容。在(!myReader.EndOfStream)时循环
,如果(info==null)中断,则丢弃代码>。在while循环之外创建并打开连接(用using语句括住while循环)。@mac007很高兴能提供帮助,您还应该看看Olivier在您的评论中提到的内容。
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();
}
}
}