Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I am trying insert some data into a MySQL database using on Duplicate key Update... But after inserting, if I click save button for several times id (auto increment) keep counting. Is there any way to fix this problem? please help me.

C#
MySqlConnection conn = new MySqlConnection(baglanti);
                conn.Open();
                MySqlCommand command = conn.CreateCommand();
                command.CommandText = "INSERT INTO hekim_terifi (personal_id,  qeyd_tarixi, hekim_ixtisas_id ) VALUES (@personal_id,  CURRENT_TIME, @hekim_ixtisas_id) on DUPLICATE KEY UPDATE hekim_ixtisas_id = '" + label3.Tag + "'";

                try
                {
                   // command.Parameters.AddWithValue("@id", "");
                    command.Parameters.AddWithValue("@personal_id", "" + label2.Tag + "");
                    command.Parameters.AddWithValue("@hekim_ixtisas_id", "" + label3.Tag + "");

                    command.ExecuteNonQuery();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

                conn.Close();
Posted
Updated 8-Dec-14 21:18pm
v3
Comments
syed shanu 9-Dec-14 3:37am    
You can display the Confirmation message box before insert .if the user click Yes then insert to database .if the user click No then dont insert to database.
Member 11284808 9-Dec-14 4:36am    
But there is "on duplicate key update", when user click yes for update, I will get same result :(

1 solution

It is clear that you use a transaction engine for MySQL (probably InnoDB)...
Let imagine a scenario:
1. START INSERT 1
2. START INSERT 2
3. INERT 1 FAILS AND ROLL BACK
4. INSERT 2 SUCCEED...

So while INSERT 2 picks his ID INSERT 1 still active so INSERT 2 will have the next ID after INSERT 1, but after than INSERT 1 drops its ID and a gap created...
But in a transnational environment there is no other way - to be always sequential you have to send your INSERT request sequentially and you lost a lot of in performance...
http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html[^]
 
Share this answer
 
Comments
Member 11284808 9-Dec-14 4:30am    
I did not get you. Could you give me an example?
Kornfeld Eliyahu Peter 9-Dec-14 4:35am    
I did!
In the sample before you INSERT 1 still running when INSERT 2 kicks in! Both need an unique id, so INSERT 1 picks 123 and INSERT 2 picks 124. Now INSERT 1 fails and does not use unique id 123, but INSERT 2 finishes and uses unique id 124. The next insert will get unique id 125 and now you have a gap...
Member 11284808 9-Dec-14 4:45am    
thanks, I got you, I have to find another way (

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900