USED: C #, Access

HAVE:
In Access, by means of the code, records are added to the database with a specific ID. How to check the unique ID of the added record?

Those. if there is an entry with the ID present in the database, then we do not add it, if not, add it. If I understand correctly, will it be a long cycle?
To add a record using the following code.

string connStringAcc = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", textBox2.Text); using (OleDbConnection connAcc = new OleDbConnection(connStringAcc)) { connAcc.Open();  // добавим строку в таблицу hist OleDbCommand command = new OleDbCommand("INSERT INTO hist(url) VALUES('" + textBox5.Text + "')", connAcc);  command.ExecuteNonQuery(); } 

QUESTION
1. How to check the unique ID of the added record?

  • 2
    If in the database to make this column unique ( UNIQUE ), then you can simply add and everything that is not unique will not be added. I really judge by mysql, but IMHO in access should also work. - Solid
  • 2
    Like this: 'ALTER TABLE hist ADD UNIQUE (id)' . Well, the query itself to change: INSERT INTO hist(id, url) VALUES('" + someid + "', '" + textBox5.Text + "')" - Solid
  • one
    Wrap command.ExecuteNonQuery (); in try {...} catch (). It makes sense to analyze possible exceptions. - Alexander Muksimov

1 answer 1

ID you have a primary key? Try this option:

 var connStringAcc = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", textBox2.Text); int id = ...; string url = textBox5.Text; using (var connAcc = new OleDbConnection(connStringAcc)) { connAcc.Open(); using (var cmd = connAcc.CreateCommand()) { cmd.CommandText = @"INSERT INTO hist(id, url) SELECT @id, @url WHERE NOT EXISTS (SELECT 1 FROM hist WHERE id = @id)"; cmd.Parameters.AddRange(new OleDbParameter[] { new OleDbParameter("@id", id), new OleDbParameter("@url", url) }); cmd.ExecuteNonQuery(); } }