int addNew(MySqlConnection mysql,string new_name){
var tr = mysql.BeginTransaction();
try{
new MySqlCommand(String.Format("select ... where name_col='{0}'",new_name), mysql, tr).ExecuteReader();
...check whether the reader is empty...
if (!read_is_empty) {..rollback/return id...}
var cmd=new MySqlCommand(String.Format("insert ... (default,...,'{0}')",new_name), mysql,tr);
cmd.ExecuteNonQuery();
int id=(int)cmd.LastInsertedId;
tr.Commit();
}catch(Exception e){
tr.Rollback();
}
}
The purpose is to create a new record if there is no existing record whose column "name_col" is new_name. Then return the created or existing record id which is the primary key with auto increment. "name_col" is unique key.
Although this can be done with "insert ignore", but the above code could work too, and get the id bring in more problem for "insert ignore".
When multiple clients run the code concurrently, sometimes duplicate entry exception is thrown. The duplicate entry is due to "name_col", not some other column.
Maybe my understanding about the transaction is wrong. What's wrong with the code?