springathing
springathing

Reputation: 465

SQL primary/identity key is not autoincrementing

Hi I'm confused as to why SQL is not auto-incrementing my Id column when I'm passing a null value in the code:

case GameStatus.WIN:
                gamefeed.Items.Add(String.Format("Congragulations, you rolled {0}. YOU WIN.", Sum));

                connect.Open();
                SqlCommand cmdwin = connect.CreateCommand();
                cmdwin.CommandType = CommandType.Text;
                cmdwin.CommandText = "insert into Round values('','" + textBox2.Text + "', '" + numRolls.ToString() + "', '"+ Point.ToString()+"', 'Win')";
                cmdwin.ExecuteNonQuery();
                connect.Close();

                break;

Any assistance or nudges towards the right direction is appreciated!

Upvotes: 0

Views: 75

Answers (2)

Mitch Wheat
Mitch Wheat

Reputation: 300559

If you have defined your Id column as an Identity column, you do not need to pass anything for the Id column in your INSERT statement (not even a placeholder).

cmdwin.CommandText = 
    "insert into Round values('" + textBox2.Text + "', '" + numRolls.ToString() + "', '"+ Point.ToString()+"', 'Win')";

Also, please note it's a very bad idea to concatenate text values (SQL Injection), use Parameters instead.

Upvotes: 2

SSD
SSD

Reputation: 1391

As already said that you dont need to paas value to identity field (autoincrement)

Your SQL should be

"insert into Round values('" + textBox2.Text + "', '" + numRolls.ToString() + "', '"+ Point.ToString()+"', 'Win')";

If you are getting error

Column name or number does not match table definition

Then you either are passing more values in insert then your columns in table Round. OR You should try giving names of your column in insert query

—Column1 is Identity
"insert into Round(Column2, Column3, Column4, Column5) values('" + textBox2.Text + "', '" + numRolls.ToString() + "', '"+ Point.ToString()+"', 'Win')";
/*Replace Column,2,3,4,5 with your respective columns in table Round*/

Upvotes: 1

Related Questions