问题
I have an identity column in the DB which is primary key and increments its value by itself. But I have a insert query in asp.net ado.net class like below:
cmd = new SqlCommand("insert into Images(Name,[Image]) VALUES ('Nature',@img)", conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@img", SqlDbType.Image).Value = img;
cmd.ExecuteNonQuery();
However, it throws me exception that it cannot be null.
My idea/goal is, I just want to insert the above two values only and the primary key column should increment by itself internally in DB. I have configured that in DB. However I don't know how to handle this error or tweak this code. Please help
回答1:
Make sure the ID
column on your Images
table is an identity column.
For example:
CREATE TABLE Images(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NOT NULL,
[Image] [image] NOT NULL)
If it is, then step through your code and make sure the parameters you are using are not null; TextBox1.Text
and img
.
Lastly, make sure there are no other non-nullable columns on the table.
回答2:
I think you havn't provided the @Name parameter I your query and but you are sending values in your paramters.
Please remove the 'Nature' value and type @Name.
cmd = new SqlCommand("insert into Images(Name,[Image]) VALUES (@Name ,@img)", conn); cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@img", SqlDbType.Image).Value = img;
cmd.ExecuteNonQuery();
来源:https://stackoverflow.com/questions/12112467/sql-identity-column-if-no-input-value-in-insert-query-in-ado-net-throws-exceptio