在写代码的时候经常遇到用到SqlDataReader之类的常用操作
using System;
using System.IO;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Web;
using System.Text;
using System.Web.UI;
namespace news
public class Tools {
public SqlDataReader SqlReader(string sql,SqlConnection connstr)
{
SqlDataReader sqldr=null;
SqlCommand cmd=new SqlCommand(sql,connstr);
if (cmd.Connection.State.ToString()=="Closed") cmd.Connection.Open();
try
{
sqldr=cmd.ExecuteReader();
}
catch(Exception e)
{
if (e!=null) sqldr=null;
}
return sqldr;
}
}
然后在其他页面调用
Tools tls=new Tools();
string sqlstr="select top 1 * from users";
if(tls.SqlReader(sqlstr,tls.Sconnstr).Read())
{
Response.Write(tls.SqlReader(sqlstr,tls.Sconnstr)["username"]);
}这样的话会报:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
using System;
using System.IO;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Web;
using System.Text;
using System.Web.UI;
namespace news
public class Tools {
public SqlDataReader SqlReader(string sql,SqlConnection connstr)
{
SqlDataReader sqldr=null;
SqlCommand cmd=new SqlCommand(sql,connstr);
if (cmd.Connection.State.ToString()=="Closed") cmd.Connection.Open();
try
{
sqldr=cmd.ExecuteReader();
}
catch(Exception e)
{
if (e!=null) sqldr=null;
}
return sqldr;
}
}
然后在其他页面调用
Tools tls=new Tools();
string sqlstr="select top 1 * from users";
if(tls.SqlReader(sqlstr,tls.Sconnstr).Read())
{
Response.Write(tls.SqlReader(sqlstr,tls.Sconnstr)["username"]);
}这样的话会报:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
{
Response.Write(tls.SqlReader(sqlstr,tls.Sconnstr)["username"]);
}
判断过程中条件语句好象不保存实例,可能没有对象值...