在一个数据库访问层中有类似以下的代码:
public class Base
.........
protected static string strConn = "Server=(local); User id=sa;Pwd=;Database=test"; public SqlDataReader ExecuteSqlDataReader(string strSQL)
{
SqlConnection myCn = new SqlConnection(strConn);
SqlCommand myCmd = new SqlCommand(strSQL,myCn);
try
{
myCn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
if(myReader.Read())
{
return myReader;
}
else
{
throw new Exception("Value Unavailable!");
}
}
catch(System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
myCn.Close();
}
然后在窗体代码中调用:
Base Login = new Base ();
string strSql="select * from table where sn='1'"; //在查询分析器中此SQL可查到一行记录
SqlDataReader dr=Login.ExecuteSqlDataReader(strSql);
while (dr.Read ())
{
TextBox1.Text=dr["username"].ToString ();
}
结果提示: 阅读器关闭时READ的尝试无效
为什么呢?应该怎么写?
public class Base
.........
protected static string strConn = "Server=(local); User id=sa;Pwd=;Database=test"; public SqlDataReader ExecuteSqlDataReader(string strSQL)
{
SqlConnection myCn = new SqlConnection(strConn);
SqlCommand myCmd = new SqlCommand(strSQL,myCn);
try
{
myCn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
if(myReader.Read())
{
return myReader;
}
else
{
throw new Exception("Value Unavailable!");
}
}
catch(System.Data.SqlClient.SqlException e)
{
throw new Exception(e.Message);
}
finally
{
myCn.Close();
}
然后在窗体代码中调用:
Base Login = new Base ();
string strSql="select * from table where sn='1'"; //在查询分析器中此SQL可查到一行记录
SqlDataReader dr=Login.ExecuteSqlDataReader(strSql);
while (dr.Read ())
{
TextBox1.Text=dr["username"].ToString ();
}
结果提示: 阅读器关闭时READ的尝试无效
为什么呢?应该怎么写?
{
myCn.Close();
}你把数据库链接给关闭了.
你在finally中关闭了数据库连接对象,当然就不可用了!
这样当sdr.Close()时,数据连接也会自动关闭.