I want to generate unique ID's for clients and store them in MySql database. It's a C# winform application, when one client enter his data like name etc. and when clicking on savebutton the ID generator needs to give him an unique ID which won't be repeated later.
I made it work, but after about 30 inserts, the generator drops a repeated number and the MySql gives this error: "Duplicate entry '76' for key 'PRIMARY'".
This is not a big error or crash, but can be annoying for long time use.
That's my code:
int minID = 1;
int maxID = 1000;
int resID;
Random CustomID = new Random();
resID = CustomID.Next(minID,maxID);
How can I check the saved ID's and clear the repeating first, then generate another number that's unique and not in the table yet?
MySql info (database table:ugyfelinfo, column: ID)
auto_increment
works well, but with my method I was able to show to saved ID to the customer when he clicked save button. Like this:
MessageBox.Show("New Costumer ID: " + resID + " - Saved in Database!")
But, now because I have auto_increment
in mysql, how can I display the delivered ID for user via MB?
The queries are like this:
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "insert into clients_db.ugyfelinfo (Ugyfel,... ) " +
" values('" + this.UgyfelTextBox.Text + "','" ..."') ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase); etc.
And I tried something like this this:
string idquery = "SELECT from clients_db.ugyfelinfo (LAST_INSERT_ID();) ";
MessageBox.Show("New user ID: "+idquery+" saved in database!");