Frage

Mysql database is like that;

userID -> primaryKey, required, unsigned integer, auto increment, unique
usermail -> unique,varchar,required

I'm creating new users. userId is auto increment. If usermail inserted before,it occurs an error. My question is this

Let's think that userID is between 1-9.(there are 9 users now). 
Somebody has inserted same usermail before and took error. 
After that,new user inserted another usermail but userID became 11 instead 10. 
Why? What should i do to make it 10?
War es hilfreich?

Lösung

Is it necessary for you to increment the userID from Database properties itself. Because what I am saying is, before inserting any records, just retrieve the last userID from database, store it in a integer variable and then increment it and insert back into database along with the new record.

Say your last user id was 9. Use this query - Select max(userID) from "your table";

int x=0;
SqlDataReader dr=com.ExecuteReader();
if(dr.HasRows)
{
    While(dr.Read())
    {
       x=Convert.ToInt32(dr.GetString(0).ToString);
    }
}
x=x+1;

Now since you have new x value, easily insert it back to database with new record. So that auto increment will be followed and even though failure occurs insertion will not be done and UserID does not increase.

Andere Tipps

When the error is being caused it seems to be inserting a new row and incrementing the uniqueid. On error you will need to query the table for the latest ID and reset the auto increment value

ALTER TABLE `table_name` AUTO_INCREMENT =new_number_here

Found Here: http://forums.mysql.com/read.php?20,16088,17748#msg-17748

You have to merge the insert clause with the select check like below .

it is a behavior of mysql that it increments the counter also for the error and for the successful insertion

INSERT INTO [table name] SELECT '[value1]', '[value2]' FROM DUAL
WHERE NOT EXISTS(
SELECT [column1] FROM [same table name]
WHERE [column1]='[value1]'
AND [column2]='[value2]' LIMIT 1    )

Here you can see the how you can prevent the insert clause insert-where-not-exists using this technique the counter will increase when data is inserted and duplicate data will be ignored

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top