I have a table with 4 columns:
id, user_name, symbol, company.
The id column is the primary key and it has autoIncrement property.
I want to add a record to the table, I use:
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO users_stocks VALUES(" +
"@user_name, @stock_symbol, @company)", connection);
cmd.Parameters.AddWithValue("@user_name", user_name);
cmd.Parameters.AddWithValue("@stock_symbol", stock_symbol);
cmd.Parameters.AddWithValue("@company", company);
int rows = cmd.ExecuteNonQuery();
connection.Close();
//rows number of record got inserted
}
catch (SqlException ex)
{
//Log exception
connection.Close();
}
But it gives me exception (I have 4 columns and I only specify 3 here).
How can I add a row with the autoIncrement column to?
You need to specify the column names in the query.
Not specifying them means the query will try to insert to all columns, which is why it fails.