SQL Identity column if no input value in insert query in ADO.NET throws exception that it can't be null

落爺英雄遲暮 提交于 2019-12-12 05:49:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!