简体   繁体   中英

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#.

        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 . 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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