使用DataReader从SQLServer检索数据时处理Null异常 [英] Handling Null Exception while retrieving data from SQLServer using DataReader
本文介绍了使用DataReader从SQLServer检索数据时处理Null异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨..
我在C#中使用Asp.net.我的后端是SQL Server.
我正在从数据库中检索数据并在标签中显示字段.
我正在使用以下代码:
Hi..
I am using Asp.net with C#.My Backend is SQL Server.
I am retrieving data from database and displaying fields in labels.
I am using following codes:
string strconSTr = ConfigurationManager.ConnectionStrings["My Connection string"].ConnectionString;
SqlConnection conn = new SqlConnection(strconSTr);
SqlCommand cmd = new SqlCommand();
conn.Open();
SqlDataReader dr;
SqlCommand comm = new SqlCommand("select * from Student where EnrolmentNo='" + TextBox1.Text + "'", conn);
dr = comm.ExecuteReader();
if(dr.HasRows && dr.Read())
{
Label1.Text = dr.GetString(1);
Label2.Text = dr.GetString(8);
Label3.Text = dr.GetString(9);
}
如果数据库包含空值,则会出现以下异常:
数据为空.无法在Null值上调用此方法或属性.
I am getting following exception if database contains Null Values:
Data is Null. This method or property cannot be called on Null values.
How to handle this exception?
推荐答案
始终建议在使用从数据库中检索到的任何对象/数据之前,应先执行NULL检查.
使用
It is always recommended that NULL check should be done before using any object/data retrieved from database.
Use
Convert.IsDBNull()
功能
一定要记得检查NULL是否用于前端(例如C#)比较,就像
Function
Do remember to check NULL in for Front End (say C#) comparison is done like
if (object == null)
但是,对于DB,应该为
However , for DB this should be
if(Convert.IsDBNull(object) == true)
Label1.Text = IIf(dr.GetString(1) Is Convert.DBNull, "", dr.GetString(1))
Label1.Text = IIf(dr.Item("FieldName") Is Convert.DBNull, "", dr.Item("FieldName"))
这篇关于使用DataReader从SQLServer检索数据时处理Null异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文