如何检查记录是否存在,并在c#中的ms访问数据库中插入

我想检查记录是否存在,如果它存在我不想插入,如果它我想在c#中的ms访问数据库中插入数据。

OleDbCommand cmd = new OleDbCommand("insert into MyTable values('" + test + "','" + test + "','" + "123" + "');", con); OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con); temp = 0; try { con.Open(); string count = (string)cmd1.ExecuteScalar(); temp = cmd.ExecuteNonQuery(); if (temp > 0) { MessageBox.Show("One Record Added"); } else { MessageBox.Show("Record not added"); } } catch { } 

任何人都可以建议我一些代码。

提前致谢。

根据某些键过滤您的Select查询。 检查是否返回特定记录的存在或不存在,并进行所需的处理。

  string cmdStr = "Select count(*) from MyTable where id = 1"; //get the existence of the record as count OleDbCommand cmd = new OleDbCommand(cmdStr, conn); int count = (int)cmd.ExecuteScalar(); if(count >0) { //record already exist } 

修改此行

  OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);