简体   繁体   English

如何检查记录是否存在并在C#中的ms Access数据库中插入

[英]How to check if record exists or not and insert in ms access database in c#

I want to check if record exists or not if it exists i dont want to insert if it bot i want to insert the data in ms access database in c#. 我想检查记录是否存在,如果它存在,我不想插入它我想在C#中的ms Access数据库中插入数据。

        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
        { }

Can Anyone suggest me some code. 任何人都可以建议我一些代码。

Thanks In Advance. 提前致谢。

Filter your Select query on the basis of some key . 根据某些关键字过滤您的Select查询。 Check if it returns for existence or non-existence of the particular record and do the processing required . 检查它是否返回特定记录的存在或不存在,并进行所需的处理。

 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 
  }

Modify this line 修改这行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM