Multiples Table in DataReader

后端 未结 3 1890
天涯浪人
天涯浪人 2020-12-01 20:29

I normally use DataSet because It is very flexible. Recently I am assigned code optimization task , To reduce hits to the database I am changing two queries in

相关标签:
3条回答
  • 2020-12-01 21:06

    Try this because this will close connection ,data reader and command once task get over , so that this will not give datareader close exception

    Also do check like this if(reader.NextResult()) to check there is next result,

    using (SqlConnection connection = new SqlConnection("connection string here"))
    {
        using (SqlCommand command = new SqlCommand
               ("SELECT Column1 FROM Table1; SELECT Column2 FROM Table2", connection))
        {
            connection.Open(); 
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    MessageBox.Show(reader.GetString(0), "Table1.Column1");
                }
    
                if(reader.NextResult())
                {
                   while (reader.Read())
                  {
                    MessageBox.Show(reader.GetString(0), "Table2.Column2");
                  }
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 21:11

    I built on Pranay Rana's answer because I like keeping it as small as possible.

    string rslt = "";
    using (SqlDataReader dr = cmd.ExecuteReader())
    {
        do
        {
            while (dr.Read())
            {
                rslt += $"ReqID: {dr["REQ_NR"]}, Shpr: {dr["SHPR_NR"]}, MultiLoc: {dr["MULTI_LOC"]}\r\n";
            }
        } while (dr.NextResult());
    }
    
    0 讨论(0)
  • 2020-12-01 21:21

    I have tried to reproduce this issue (also because i haven't used multiple tables in a reader before). But it works as expected, hence i assume that you've omitted the related code.

    Here's my test code:

    using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
    {
        using (var cmd = new SqlCommand("SELECT TOP 10 * FROM tabData; SELECT TOP 10 * FROM tabDataDetail;", con))
        {
            int rowCount = 0;
            con.Open();
            using (IDataReader rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    String object1 = String.Format("Object 1 in Row {0}: '{1}'", ++rowCount, rdr[0]);
                }
                if (rdr.NextResult())
                {
                    rowCount = 0;
                    while (rdr.Read())
                    {
                        String object1 = String.Format("Object 1 in Row {0}: '{1}'", ++rowCount, rdr[0]);
                    }
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题