ADO.NET SqlCommand:无法将 NULL 值插入列中
sCnd = "INSERT INTO .dbo.Table(Col1, Col2, Col3) Values (1,2,3);
using (DbCommand tempCommand2 = CommandFactory.CreateCommand(db))
{
tempCommand2.CommandText = sCmd;
tempCommand2.ExecuteNonQuery();
}
Table还有一个不允许为null的Col4。
错误: 无法将 NULL 值插入列 Col4
当我在 Management Studio 中执行 sCmd 时,一切正常。
为什么我会遇到异常?
sCnd = "INSERT INTO .dbo.Table(Col1, Col2, Col3) Values (1,2,3);
using (DbCommand tempCommand2 = CommandFactory.CreateCommand(db))
{
tempCommand2.CommandText = sCmd;
tempCommand2.ExecuteNonQuery();
}
Table has also a Col4 that does not allow null.
Error: Cannot insert the value NULL into column Col4
When I execute the sCmd in the Management Studio everything works fine.
Why do I get the exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这就是你的答案。如果 Management Studio 仍然可以工作,它可能会插入默认值?
There is your answer. If Management Studio works anyway, it is probably inserting a default value?
您之所以会出现异常,是因为您没有为
Col4
列插入值,该列不允许null
,而且我只能假设它没有默认值。但你好像问错了问题;你不是想问,为什么查询在SSMS中运行吗?
我怀疑这个问题的答案可能隐藏在实际语法中的某个地方,而您选择不包含该语法。
You get the exception because you are not inserting a value for the
Col4
column, which does not allownulls
and, I can only assume, does not have a default value.But it seems like you've asked the wrong question; don't you mean to be asking, why does the query run in SSMS?
I suspect the answer to that question would be buried somewhere in the actual syntax, which you have elected not to include.
如果您没有指定列的值,则采用
NULL
,除非有约束
另有规定。由于
Col4
不允许NULL
并且看起来它没有default
值constraint
这就是为什么你得到了错误。您没有显示在 SSMS 中执行的 SQL,但我猜,不同的数据库(生产/开发)、不同的表?
If you don't specify a value for a column
NULL
is taken, unless there is aconstraint
which says otherwise.As
Col4
doesn't allowNULL
and looks like it doesn't have adefault
valueconstraint
that is why you get the error.You haven't shown the SQL you are executing in SSMS, but I'd guess, different database (production/development), different table?