为什么我看书上的例子 在每个按钮下都把 SqlConnection SqlCommand SqlReader写了一遍
然后我自己想用封装的方法 结果报错为 未将对象引用设置到对象的实例。
public class DataAccess
{
public static string ConnStr="Data Source=.\\sqlexpress;Initial Catalog=学生信息管理;Integrated Security=True;Pooling=False";
public SqlDataReader GetReader(string sqlText)
{
SqlConnection conn = new SqlConnection(ConnStr);
SqlCommand command = new SqlCommand(sqlText,conn);
SqlDataReader dr = null;
try
{
conn.Open();
dr = command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception e)
{
dr.Close();/就是这里报错了
conn.Dispose();
command.Dispose();
throw new Exception(e.ToString());//
}
return dr;
}
}
这是登陆按钮下的事件
protected void Btnlogin_Click(object sender, EventArgs e)
{
string name = this.TBname.Text.Trim();
string password = this.TBpwd.Text.Trim();
DataAccess da=new DataAccess(); string sqlText="select * from 用户信息 where 用户名=‘"+name+"' and 密码='"+password+"’"; SqlDataReader reader = da.GetReader(sqlText);
if (reader.Read()==true)
{
Session["userName"] = name;
this.Lblstate.Text = "用户" + name + "登陆成功";
}
}
然后我自己想用封装的方法 结果报错为 未将对象引用设置到对象的实例。
public class DataAccess
{
public static string ConnStr="Data Source=.\\sqlexpress;Initial Catalog=学生信息管理;Integrated Security=True;Pooling=False";
public SqlDataReader GetReader(string sqlText)
{
SqlConnection conn = new SqlConnection(ConnStr);
SqlCommand command = new SqlCommand(sqlText,conn);
SqlDataReader dr = null;
try
{
conn.Open();
dr = command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception e)
{
dr.Close();/就是这里报错了
conn.Dispose();
command.Dispose();
throw new Exception(e.ToString());//
}
return dr;
}
}
这是登陆按钮下的事件
protected void Btnlogin_Click(object sender, EventArgs e)
{
string name = this.TBname.Text.Trim();
string password = this.TBpwd.Text.Trim();
DataAccess da=new DataAccess(); string sqlText="select * from 用户信息 where 用户名=‘"+name+"' and 密码='"+password+"’"; SqlDataReader reader = da.GetReader(sqlText);
if (reader.Read()==true)
{
Session["userName"] = name;
this.Lblstate.Text = "用户" + name + "登陆成功";
}
}
再关闭dataAdapter
最后关闭数据库
SqlCommand command = new SqlCommand(sqlText,conn);
SqlDataReader dr = null;
try
{
conn.Open();//说不定你这句就报错了,然后catch里面的代码!
这时候dr=null,dr.Close()当然要报错
dr = command.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception e)
{
dr.Close();/就是这里报错了[/color
[color=#FF0000]]//在这加上一个判断,如果dr!=null而且dr的状态是open的才关闭!
conn.Dispose();
command.Dispose();
throw new Exception(e.ToString());//
}
楼主加了这句,所以再dr.close()就报错了
这是由程序过程的设计漏洞“dr并不是一定在有实例对象时被关闭”导致,所以需要改变程序过程以下是我在你代码上做的修改:
public SqlDataReader GetReader(string sqlText)
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
SqlCommand command = new SqlCommand(sqlText, conn);
SqlDataReader dr = null;
try
{
conn.Open();
dr = command.ExecuteReader(CommandBehavior.CloseConnection);
dr.Close();
}
catch (Exception e)
{
throw new Exception(e.ToString());//
}
finally
{
conn.Close();
command.Dispose();
}
}
}
上面程序的dr.Close(); 可以不要
在代码的最后加上 return dr; 即可由于dr 为null是 不需要close();所以无需做关闭操作