Should I call SqlDataReader.HasRows if I am calling SqlReader.Read

后端 未结 5 1743
一向
一向 2020-12-10 01:46

Trying to see if it is beneficial to add an if (dr.HasRows) before the while (dr.read()) function. I mean, technically if it doesn\'t have rows it

相关标签:
5条回答
  • 2020-12-10 02:07

    Be careful. HasRows() returns false for my CTE query, even though there are rows (437 rows actually).

    0 讨论(0)
  • 2020-12-10 02:11

    No..It is not mandatory to check (dr.HasRows) if the DataReader contains any row or not.

    Read() will return False if there are no more rows to fetch, but Reader.HasRows is much more telling as to what it does than Read() so it would be a good practice to use Reader.HasRows because you may accidentally do something other than Read() which may fall into exception.

    0 讨论(0)
  • 2020-12-10 02:12

    It's not mandatory to check if the DataReader has rows (dr.HasRows). The Read() method will return true if there is more data to read and false if there's no more data, thus breaking the while-loop.

    0 讨论(0)
  • 2020-12-10 02:18

    try

                string myconnection = "datasource= localhost;port=3306;username=root;password=root;";
                MySqlConnection myconn = new MySqlConnection(myconnection);
    
                //MySqlDataAdapter mydata = new MySqlDataAdapter();
                MySqlDataReader myreader;
    
                MySqlCommand SelectCommand = new MySqlCommand("select *from student_info.student_info where username= '" + textBox1.Text +" 'and password=' " + textBox2.Text +"';",myconn );
    
    
                myconn.Open();
    
                myreader = SelectCommand.ExecuteReader();
                int count = 0;
                if (myreader.HasRows) //returing false but i have 4 row
                {
                    while (myreader.Read()) //returing false 
                    {
                        MessageBox.Show("in button3");
                        count = count + 1;
                    }
                }
    

    your opinion required

    0 讨论(0)
  • 2020-12-10 02:21

    I think this is mostly for stored procedures which may or may not have data (one or more result sets) and it is "easier" to check first in case you also do other stuff than the while loop (i.e. initialize header/footer etc. when there is data).

    0 讨论(0)
提交回复
热议问题