Home Database Mysql Tutorial DBNull和Null的区别

DBNull和Null的区别

Jun 07, 2016 pm 04:20 PM
null the difference

DBNull 类 表示不存在的值。无法继承此类。 命名空间: System 程序集: mscorlib(在 mscorlib.dll 中) DBNull 类表示一个不存在的值。例如,在数据库的表中,某一行的某列中可能不包含任何数据。即,该列被视为根本不存在,而不只是没有值。一个表示不存在

   DBNull 类

  表示不存在的值。无法继承此类。

  命名空间: System

  程序集: mscorlib(在 mscorlib.dll 中)

  DBNull 类表示一个不存在的值。例如,在数据库的表中,某一行的某列中可能不包含任何数据。即,该列被视为根本不存在,而不只是没有值。一个表示不存在的列的 DBNull 对象。此外,COM 互操作使用 DBNull 类来区分 VT_NULL 变量(指示不存在的值)和 VT_EMPTY 变量(指示未指定的值)。

  DBNull 类型是一个单独的类,这意味着只有一个 DBNull 对象存在。DBNull::.Value 成员表示唯一的 DBNull对象。DBNull::.Value 可用于将不存在的值显式分配给数据库字段,但大多数 ADO.NET 数据提供程序在字段没有有效值时会自动分配 DBNull 值。您可以通过将从数据库字段检索到的值传递给 DBNull.Value.Equals 方法,确定该字段值是否为 DBNull 值。然而,有些语言和数据库对象提供一些方法,可以更容易地确定数据库字段值是否为 DBNull::.Value.这些方法包括 Visual Basic 的 IsDBNull 函数、Convert::.IsDBNull 方法、DataTableReader::.IsDBNull 方法和 IDataRecord::.IsDBNull 方法。

  请勿将面向对象的编程语言中的 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing) 概念与 DBNull对象混淆。在面向对象的编程语言中,nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing) 表示不存在对某个对象的引用。DBNull 则表示未初始化的变量或不存在的数据库列。

  备注

  示例

  下面的示例调用 DBNull.Value.Equals 方法,来确定联系人数据库中的数据库字段是否具有有效值。如果具有有效值,字段值将被追加到在标签中输出的字符串中。

  C# 中的用法

  private void OutputLabels(DataTable dt)

  {

  string label;

  // Iterate rows of table

  foreach (DataRow row in dt.Rows)

  {

  int labelLen;

  label = String.Empty;

  label += AddFieldValue(label, row, "Title");

  label += AddFieldValue(label, row, "FirstName");

  label += AddFieldValue(label, row, "MiddleInitial");

  label += AddFieldValue(label, row, "LastName");

  label += AddFieldValue(label, row, "Suffix");

  label += "/n";

  label += AddFieldValue(label, row, "Address1");

  label += AddFieldValue(label, row, "AptNo");

  label += "/n";

  labelLen = label.Length;

  label += AddFieldValue(label, row, "Address2");

  if (label.Length != labelLen)

  label += "/n";

  label += AddFieldValue(label, row, "City");

  label += AddFieldValue(label, row, "State");

  label += AddFieldValue(label, row, "Zip");

  Console.WriteLine(label);

  Console.WriteLine();

  }

  }

  private string AddFieldValue(string label, DataRow row,

  string fieldName)

  {

  if (! DBNull.Value.Equals(row[fieldName]))

  return (string) row[fieldName] + " ";

  else

  return String.Empty;

  }

  初学数据库编程我们可能会有一些对"空值"的疑问,比如通过编程新建的一个表中所有数据皆显示为,手动添加并删除文字后又变成了空白;一个字符串类型的字段,明明没有填值,却不等于"";用ADO.NET从数据库中取值,每遇到有的就出错……这需要我们正确认识。NET和SQL Server中几种不同的"空值".

  1、真正的空值,也就是"没有输入的值",可以出现在大多数类型的字段中(如果没有别的约束条件),SQL server中表示为null,显示为,手工在SQL server企业管理器中输入的方法是按Ctrl+0.它在。NET中对应System.DBNull.Value.在T-SQL命令中,判断一个值是不是空值,要用"is null"而不是"= null";处理空值有个ISNULL函数,它使用指定的值替换null.用ADO.NET从数据库得到的空值无法自动转化为空字符串或Nothing,须手动检测:如果得到System.DBNull.Value,则赋给数据对象Nothing或其它自定义的有意义的值。

  2、空字符串(零长度字符串),只出现在字符串类型(如nvarchar)的字段中,SQL server中表示为'',显示为空白,手工在SQL server企业管理器中输入时清空一个单元格即可。它在。NET中对应System.String.Empty,也就是我们常用的"".在T-SQL命令中处理空字符串和处理一般的字符串没什么区别。用ADO.NET从数据库得到的空字符串也和一般的字符串没什么区别。

  DBNull简介

  DBNull在DotNet是单独的一个类型 System.DBNull .它只有一个值 DBNull.Value .DBNull 直接继承 Object ,所以 DBNull 不是 string , 不是 int , 也不是 DateTime …

  但是为什么 DBNull 可以表示数据库中的字符串,数字,或日期呢?原因是DotNet储存这些数据的类(DataRow等)都是以 object 的形式来储存数据的。对于 DataRow , 它的 row[column] 返回的值永远不为 null , 要么就是具体的为column 的类型的值 . 要么就是 DBNull . 所以 row[column].ToString() 这个写法永远不会在ToString那里发生NullReferenceException.

  DBNull 实现了 IConvertible . 但是,除了 ToString 是正常的外,其他的ToXXX都会抛出不能转换的错误。

  在 IDbCommand(OleDbCommand,SqlCommand…) 的ExecuteScalar的返回值中,情况可以这样分析:

  select 1 这样返回的object是 1 select null 这样返回的是DBNull.Value select isnull(null,1) 返回的是 1 select top 0 id from table1 这样返回的值是null select isnull(id,0) from table1 where 1=0 返回的值是null

  这里 ExecuteScalar 的规则就是,,返回第一列,第一行的数据。如果第一列第一行不为空,那么ExecuteScalar就直接对应的DotNet的值。如果有第一行,但是第一列为空,那么返回的是 DBNull .如果一行都没有,那么ExecuteScalar就返回null

  规则就是这样的。这里容易犯的一个错误是,把ExecuteScalar返回DBNull与null的情况混淆,例如:

  string username=cmd.ExecuteScalar()。ToString();

  除非你认为cmd执行后,肯定至少有一行数据,否则这里就会出错。

  又或者 select id from usertable where username=@name 这样的sql语句,如果找不到记录,那么ExecuteScalar则会返回null,所以千万不要

  int userid=Convert.ToInt32(cmd.ExecuteScalar());

  或者你会这样写 SQL 语句:select isnull(id,0) from usertable where username=@name

  但是 int userid=Convert.ToInt32(cmd.ExecuteScalar()); 依然会出错,因为上面的语句不成立时,仍然是不返回任何行。

  对于IDbDataParameter(OleDDbParameter,SqlParameter)的Value,如果为null,则代表该参数没有指定,或者是代表DEFAULT.如果为DBNull.Value,则代表SQL中的NULL

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

deepseek What is the difference between r1 and v3 version deepseek What is the difference between r1 and v3 version Feb 19, 2025 pm 03:24 PM

DeepSeek: In-depth comparison between R1 and V3 versions helps you choose the best AI assistant! DeepSeek already has tens of millions of users, and its AI dialogue function has been well received. But are you confused when facing the R1 and V3 versions? This article will explain the differences between the two in detail to help you choose the most suitable version. The core difference between DeepSeekR1 and V3 version: Features The design goal of the V3 version focuses on complex problem reasoning, deep logic analysis, multi-functional large language model, focusing on scalability and efficiency architecture and parameter reinforcement learning optimization architecture, parameter scale 1.5 billion to 70 billion MoE hybrid Expert architecture, total parameters are as high as 671 billion, each token is activated by 37 billion

Summary of FAQs for DeepSeek usage Summary of FAQs for DeepSeek usage Feb 19, 2025 pm 03:45 PM

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI ​​model through API or Ollama. What is breaking limit

Does Bitcoin have stocks? Does Bitcoin have equity? Does Bitcoin have stocks? Does Bitcoin have equity? Mar 03, 2025 pm 06:42 PM

The cryptocurrency market is booming, and Bitcoin, as a leader, has attracted the attention of many investors. Many people are curious: Do Bitcoin have stocks? The answer is no. Bitcoin itself is not a stock, but investors can indirectly invest in Bitcoin-related assets through various channels, which will be explained in detail in this article. Alternatives to Bitcoin Investment: Instead of investing directly in Bitcoin, investors can participate in the Bitcoin market by: Bitcoin ETF: This is a fund traded on the stock trading market, whose asset portfolio contains Bitcoin or Bitcoin futures contracts. This is a relatively convenient option for investors who are accustomed to stock investments, without having to hold Bitcoin directly. Bitcoin Mining Company Stocks: These companies' business is Bitcoin mining and holding Bitcoin

What is the difference between pre-market and after-market trading? Detailed explanation of the differences between pre-market and after-market trading What is the difference between pre-market and after-market trading? Detailed explanation of the differences between pre-market and after-market trading Mar 03, 2025 pm 11:54 PM

In traditional financial markets, pre-market and after-market trading refers to trading activities outside the regular trading period. Although the cryptocurrency market is trading around the clock, trading platforms like Bitget also offer similar features, especially some comprehensive platforms that trade stocks and cryptocurrencies at the same time. This article will clarify the differences in pre-market and after-market trading and explore its impact on currency price. Four major differences between pre-market and after-market trading: The main differences between pre-market and after-market trading and regular trading periods are in four aspects: trading time, liquidity, price fluctuations and trading volume: Trading time: Pre-market trading occurs before the official trading starts, and after-market trading is carried out after the regular trading ends. Liquidity: The liquidity of pre- and after-hours trading is low, there are few traders, and the bid and offer price difference is large; while the liquidity is high during the regular trading period, the price is

Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Why is Bittensor said to be the 'bitcoin' in the AI ​​track? Mar 04, 2025 pm 04:06 PM

Original title: Bittensor=AIBitcoin? Original author: S4mmyEth, Decentralized AI Research Original translation: zhouzhou, BlockBeats Editor's note: This article discusses Bittensor, a decentralized AI platform, hoping to break the monopoly of centralized AI companies through blockchain technology and promote an open and collaborative AI ecosystem. Bittensor adopts a subnet model that allows the emergence of different AI solutions and inspires innovation through TAO tokens. Although the AI ​​market is mature, Bittensor faces competitive risks and may be subject to other open source

Is there any difference between South Korean Bitcoin and domestic Bitcoin? Is there any difference between South Korean Bitcoin and domestic Bitcoin? Mar 05, 2025 pm 06:51 PM

The Bitcoin investment boom continues to heat up. As the world's first decentralized digital asset, Bitcoin has attracted much attention on its decentralization and global liquidity. Although China was once the largest market for Bitcoin, policy impacts have led to transaction restrictions. Today, South Korea has become one of the major Bitcoin markets in the world, causing investors to question the differences between it and its domestic Bitcoin. This article will conduct in-depth analysis of the differences between the Bitcoin markets of the two countries. Analysis of the differences between South Korea and China Bitcoin markets. The main differences between South Korea and China’s Bitcoin markets are reflected in prices, market supply and demand, exchange rates, regulatory supervision, market liquidity and trading platforms. Price difference: South Korea’s Bitcoin price is usually higher than China, and this phenomenon is called “Kimchi Premium.” For example, in late October 2024, the price of Bitcoin in South Korea was once

Vertical proxy: Application scenarios and interpretation of disruptive potential of encryption native proxy Vertical proxy: Application scenarios and interpretation of disruptive potential of encryption native proxy Mar 04, 2025 am 10:21 AM

Artificial intelligence agents (AIAgents) are rapidly integrating into daily operations of enterprises, from large companies to small businesses, almost all areas have begun to be used, including sales, marketing, finance, law, IT, project management, logistics, customer service and workflow automation. We are moving from an era of manual processing of data, performing repetitive tasks, and using Excel tables to an era of autonomous operation by AI agents around the clock, which not only improves efficiency but also significantly reduces costs. Application case of AI agents in Web2: YCombinator's Perspective Apten: A sales and marketing optimization tool combining AI and SMS technology. BildAI: A model that can read architectural blueprints,

Pepe bought and sold out in a big way, is MUTM a smarter investment in 2025? Pepe bought and sold out in a big way, is MUTM a smarter investment in 2025? Mar 03, 2025 pm 07:09 PM

After the surge in PEPE, can MUTM become a more stable investment choice in 2025? PEPE (PEPE) has made early investors profitable, but its violent price fluctuations have also made many people question its long-term prospects. As the meme currency market continues to turbulently, traders are beginning to focus on projects with more fundamental advantages, and MutuumFinance (MUTM) is one of them. This is a decentralized lending platform focusing on practical financial applications. Unlike PEPE, which relies on speculative speculation, MUTM builds a structured DeFi ecosystem where users can borrow and earn passive income. Its pre-sale has exceeded one million US dollars, the first phase of token sales rate exceeds 97%, early investment

See all articles