使用 DBNull 或 null 插入/更新数据? [英] INSERT / UPDATE data using DBNull or null?
问题描述
修改 SQL Server 数据库中的数据时,您可以使用 System.DBNull.Value
或 null
来表示 NULL
值.这两个都可以工作,并将适当的值设置为 NULL
.
When modifying data in a SQL Server database you can use either System.DBNull.Value
or null
to represent a NULL
value. Both of these will work and will set the proper value to NULL
.
我的问题是 - 哪些是首选,为什么?在某些情况下,是否应该使用一个代替另一个?
My question is - which of these is preferred, and why? Are there certain cases where one should be used in place of the other?
推荐答案
来自 System.DBNull.Value != null,并通过测试此代码:
From System.DBNull.Value != null, and by testing this code:
var result = (System.DBNull.Value == null); // this is always false
我们可以看到 CLR 并没有以同样的方式对待它们.从数据库中检索数据时,我们需要检查 DBNull.Value
而不是 null
引用.
We can see that the CLR doesn't treat them the same way. When retrieving data from a database we need to check for DBNull.Value
and not a null
reference.
尽管我们使用 INSERT
或 UPDATE
数据无关紧要,但为了一致性,我倾向于坚持使用 DBNull.Value
通过数据访问代码.
Although it doesn't matter which we use to INSERT
or UPDATE
data, I would tend to stick with DBNull.Value
for consistency through data access code.
问题中有多种其他意见C#数据库访问:DBNullvs 空
这篇关于使用 DBNull 或 null 插入/更新数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!