繁体   English   中英

将NextResult功能与datareader一起使用时出错

[英]Error while using NextResult fuction with datareader

将NextResult功能与datareader一起使用时出错

无法获得第二个表结果,并且在第二个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)
   {

   }
}

我试过的

我曾尝试使用以下代码获得多个结果

在这种情况下,我将仅使用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);

还要注意,您永远不要串联字符串来构建sql命令。 始终使用参数。

如果sqlReader.IsClosedfalse并且NextResults根据此论坛返回false ,则DataTable.Load关闭sqlReader

因此,代替:

if (sqlReader.NextResult())

您需要使用:

if (!sqlReader.IsClosed && sqlReader.NextResult() && sqlReader.HasRows)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM