ExecuteReader需要一个打开的可用连接.连接的当前状态为连接中.在执行reader
本文关键字:连接 状态 reader 执行 一个 ExecuteReader | 更新日期: 2023-09-27 18:02:41
这里我使用我的webmethod。但是当我要连接时,它显示了这个错误。但是我认为我的代码很好。
ExecuteReader需要一个打开且可用的连接。连接的当前状态是正在连接。
MyCode
public static List<CommonPages> GetCommonPagesDescription(int Type)
{
List<CommonPages> CommonPageDescription = new List<CommonPages>();
try
{
SqlCommand comGetAllFiles = new SqlCommand("GetCommonPageDescriptions", conDB);
comGetAllFiles.CommandType = CommandType.StoredProcedure;
if (conDB.State == ConnectionState.Closed)
conDB.Open(); // <-- Debugger Skip this & goto next line
comGetAllFiles.Parameters.Add("@Type", SqlDbType.Int);
comGetAllFiles.Parameters["@Type"].Value = Type;
SqlDataReader rdr = comGetAllFiles.ExecuteReader();//<-- error generating here
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
CommonPageDescription.Add(new CommonPages
{
Id = (int)r["Id"],
Description = r["Description"].ToString(),
Type = (int)r["Type"],
UpdatedDate = (DateTime)r["UpdatedDate"],
UpdatedBy = (Guid)r["UpdatedBy"]
});
}
}
catch (Exception ee)
{
}
finally
{
conDB.Close();
}
return CommonPageDescription;
}
conDB Initialized here
static SqlConnection conDB = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
conDB
必须是共享连接?利用连接池可能不是个好主意。
要解决这个问题,可以考虑每个请求打开和关闭一个connection
。不要介意巫魔说这是低效的,事实上你想要打开/关闭连接尽可能少,但有时你需要去DB一个单一的原因。有一些方法可以更好地共享连接,例如使用context
模式。但是为了解决您的直接问题,您的DB以这种方式调用。
try
{
using( System.Data.Common.DbConnection conn = CreateConnection() )
{
//create your command...
//create your reader/or execute your command...
}
}
尝试在连接未打开时打开连接,而不是在连接关闭时打开连接。
public static List<CommonPages> GetCommonPagesDescription(int Type)
{
List<CommonPages> CommonPageDescription = new List<CommonPages>();
try
{
SqlCommand comGetAllFiles = new SqlCommand("GetCommonPageDescriptions", conDB);
comGetAllFiles.CommandType = CommandType.StoredProcedure;
if (conDB.State != ConnectionState.Open)
conDB.Open(); // <-- Debugger Skip this & goto next line
comGetAllFiles.Parameters.Add("@Type", SqlDbType.Int);
comGetAllFiles.Parameters["@Type"].Value = Type;
SqlDataReader rdr = comGetAllFiles.ExecuteReader();//<-- error generating here
DataTable dt = new DataTable();
dt.Load(rdr);
foreach (DataRow r in dt.Rows)
{
CommonPageDescription.Add(new CommonPages
{
Id = (int)r["Id"],
Description = r["Description"].ToString(),
Type = (int)r["Type"],
UpdatedDate = (DateTime)r["UpdatedDate"],
UpdatedBy = (Guid)r["UpdatedBy"]
});
}
}
catch (Exception ee)
{
}
finally
{
conDB.Close();
}
return CommonPageDescription;
}