ASP.NET 三成架构 SqlDataReader 问题
我在一个方法内,调用了2次SqlDataReader,在第一次还未关闭前又调用了第二次,这时报错,请问如何解决?publicstaticStudentModelssele...
我在一个方法内,调用了2次SqlDataReader,在第一次还未关闭前又调用了第二次,这时报错,请问如何解决?
public static StudentModels select()
{
string sql = "select * from student";
SqlDataReader dr = DB.dr(sql);
if (dr.Read())
{
StudentModels sm = new StudentModels();
sm.Id = Convert.ToInt32(dr["id"]);
sm.Name = dr["name"].ToString();
sm.Sex = dr["sex"].ToString();
sm.Cm = ClassService.selectAll(dr["classID"].ToString());
dr.Close();
return sm;
}
public static ClassModels selectAll(string classID)
{
string sql = "select * from class where classID = '" + classID + "'";
SqlDataReader dr = DB.dr(sql);
if (dr.Read())
{
ClassModels cm = new ClassModels();
cm.Id = Convert.ToInt32(dr["id"]);
cm.ClassID = dr["classID"].ToString();
dr.Close();
return cm;
} 展开
public static StudentModels select()
{
string sql = "select * from student";
SqlDataReader dr = DB.dr(sql);
if (dr.Read())
{
StudentModels sm = new StudentModels();
sm.Id = Convert.ToInt32(dr["id"]);
sm.Name = dr["name"].ToString();
sm.Sex = dr["sex"].ToString();
sm.Cm = ClassService.selectAll(dr["classID"].ToString());
dr.Close();
return sm;
}
public static ClassModels selectAll(string classID)
{
string sql = "select * from class where classID = '" + classID + "'";
SqlDataReader dr = DB.dr(sql);
if (dr.Read())
{
ClassModels cm = new ClassModels();
cm.Id = Convert.ToInt32(dr["id"]);
cm.ClassID = dr["classID"].ToString();
dr.Close();
return cm;
} 展开
2个回答
展开全部
DataReader 使用一次后必须关闭,要不然下一次就不能打开,这是我写的一读取方法\_____________
SqlDataReader db = null;
SqlCommand cmd = new SqlCommand();
if (cmd == null) throw new ArgumentNullException("cmd");
if (commandText.Equals(string.Empty) || commandText.Length == 0) throw new ArgumentException("commandText");
Connect();
cmd.Connection = cn;
cmd.CommandType = commType;
cmd.CommandText = commandText;
if (par != null)
foreach (SqlParameter p in par)
cmd.Parameters.Add(p);
if (cn.State != ConnectionState.Open)
cn.Open();
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (dr.Read())
{
db = dr;
}
dr.Close();
dr.Dispose();
}
Close();
return db;
SqlDataReader db = null;
SqlCommand cmd = new SqlCommand();
if (cmd == null) throw new ArgumentNullException("cmd");
if (commandText.Equals(string.Empty) || commandText.Length == 0) throw new ArgumentException("commandText");
Connect();
cmd.Connection = cn;
cmd.CommandType = commType;
cmd.CommandText = commandText;
if (par != null)
foreach (SqlParameter p in par)
cmd.Parameters.Add(p);
if (cn.State != ConnectionState.Open)
cn.Open();
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (dr.Read())
{
db = dr;
}
dr.Close();
dr.Dispose();
}
Close();
return db;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询