如果在ADO.NET中插入查询中没有输入值,则SQL Identity列将引发异常,该异常不能为null [英] SQL Identity column if no input value in insert query in ADO.NET throws exception that it can't be null

查看:78
本文介绍了如果在ADO.NET中插入查询中没有输入值,则SQL Identity列将引发异常,该异常不能为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有一个标识列,它是主键,它自己增加其值。但是我在asp.net ado.net类中有一个插入查询,如下所示:

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.

我的想法/目标是,我只想插入上述两个值,并且主键列应在DB内部自行增加。我已经在数据库中配置了它。但是,我不知道如何处理此错误或调整此代码。请帮助

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

推荐答案

确保<$ c上的 ID 列$ c>图像表是一个标识列。

Make sure the ID column on your Images table is an identity column.

例如:

CREATE TABLE Images(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](100) NOT NULL,
    [Image] [image] NOT NULL)

如果是,则逐步执行代码并确保您使用的参数不为空; TextBox1.Text img

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.

这篇关于如果在ADO.NET中插入查询中没有输入值,则SQL Identity列将引发异常,该异常不能为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆