C#There is already an open DataReader associated with this Connection which must be closed
string constr = "Server=.;user=sa;pwd=*********;database=mydb";
SqlConnection myCon = new SqlConnection(constr);
try
{
using (myCon)
{
myCon.Open();
Console.WriteLine("数据连接已经打开");
string sql = "select max(age) from mytable003";
SqlCommand mycommand = new SqlCommand(sql, myCon);
int t = 0;
t = (int)mycommand.ExecuteScalar();
Console.WriteLine("最大年龄是" + t + "岁");
myCon.Close();
}
}
catch { }
finally
{
myCon.Close();
Console.WriteLine("数据库已经关闭");
}
Console.ReadKey();
这段代码是运行正常的,接下来上面的代码注释掉,运行下面的代码后出现提示:There is already an open DataReader associated with this Connection which must be closed
string constr = "Server=.;user=sa;pwd=*********;database=mydb";
SqlConnection myCon = new SqlConnection(constr);
try
{
using (myCon)
{
myCon.Open();
string sql = "select * from mytable003";
SqlCommand mycommand = new SqlCommand(sql, myCon);
mycommand.ExecuteReader();
SqlDataReader mydr;
mydr = mycommand.ExecuteReader();
if (mydr.HasRows)
{
Console.WriteLine("该表中存在数据");
}
else
{
Console.WriteLine("该表中没有数据");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
finally
{
myCon.Close();
Console.WriteLine("数据库已经关闭");
}
Console.ReadKey();
所以是第一段代码出现了没有关闭的datareader吗?该怎么处理,网上看了一些东西,但是还是弄不明白,数据库用的是sql server2012