[英]Error while using NextResult fuction with datareader
Error while using NextResult fuction with datareader 将NextResult功能与datareader一起使用时出错
cannot get second table result and error on second NextResult line " invalid attempt to call nextresult when reader is closed " 无法获得第二个表结果,并且在第二个NextResult行上显示错误“关闭阅读器时,无效尝试调用nextresult”
using (SqlConnection myCon = DBCon)
{
try
{
string Qry = @"SELECT [OPSProcedure],[OPSInsertedOn],[OPSInsertedBy]
FROM [Operation] where OPSID = '" + opId + "';";
Qry += @"SELECT LKCPID FROM dbo.ConcurrentProcedure where CPOperationID = '" + opId + "';";
Qry += @"SELECT IOperaitonID FROM dbo.LkupIntraOperativeAdverseEvents where IOperaitonID = '" + opId + "';";
myCon.Open();
SqlCommand myCommand = new SqlCommand(Qry, myCon);
myCommand.CommandType = CommandType.Text;
SqlDataReader sqlReader = myCommand.ExecuteReader();
DataSet dr = new DataSet();
if (sqlReader.HasRows)
{
dt1.Load(sqlReader);
if(sqlReader.NextResult())
{
dt2.Load(sqlReader);
}
if (sqlReader.NextResult())
{
dt3.Load(sqlReader);
}
}
sqlReader.Close();
}
catch (Exception ex)
{
}
}
What I have tried: 我试过的
i have tried using below code for multiple result 我曾尝试使用以下代码获得多个结果
In this context I would simply use an SqlDataAdapter to make one single call and fill all your tables 在这种情况下,我将仅使用SqlDataAdapter进行一次调用并填充所有表
using (SqlConnection myCon = DBCon)
{
try
{
string Qry = @"SELECT [OPSProcedure],[OPSInsertedOn],[OPSInsertedBy]
FROM [Operation] where OPSID = @id;
SELECT LKCPID FROM dbo.ConcurrentProcedure
where CPOperationID = @id;
SELECT IOperaitonID FROM dbo.LkupIntraOperativeAdverseEvents
where IOperaitonID = @id";
myCon.Open();
SqlDataAdapter da = new SqlDataAdapter(Qry, myCon);
da.SelectCommand.Parameter.Add("@id", SqlDbType.NVarChar).Value = opID;
DataSet ds = new DataSet();
da.Fill(ds);
// Test...
Console.WriteLine(ds.Tables[0].Rows.Count);
Console.WriteLine(ds.Tables[1].Rows.Count);
Console.WriteLine(ds.Tables[2].Rows.Count);
Notice also that you should never concatenate strings to build sql commands. 还要注意,您永远不要串联字符串来构建sql命令。 Always use parameters.
始终使用参数。
DataTable.Load
closes the sqlReader
if sqlReader.IsClosed
is false
and NextResults
returns false
as per this forum . 如果
sqlReader.IsClosed
为false
并且NextResults
根据此论坛返回false
,则DataTable.Load
关闭sqlReader
。
As such, instead of: 因此,代替:
if (sqlReader.NextResult())
you need to use: 您需要使用:
if (!sqlReader.IsClosed && sqlReader.NextResult() && sqlReader.HasRows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.