SQL Data Reader: Invalid attempt to read when no data is present

。_饼干妹妹 提交于 2020-01-03 03:31:08

问题


I am trying to use a SqlDataReader to run a query and then display the results in a messagebox, but I keep getting the error

Invalid attempt to read when no data is present.

Here is my code.

 public void button1_Click(object sender, EventArgs e)
 {
    string results = "";
    using (SqlConnection cs = new SqlConnection(@"Server=100-nurex-x-001.acds.net;Database=Report;User Id=reports;Password=mypassword"))
    {
         cs.Open();
         string query = "select stationipaddress from station where stationname = @name";
         using (SqlCommand cmd = new SqlCommand(query, cs))
         {
              // Add the parameter and set its value -- 
              cmd.Parameters.AddWithValue("@name", textBox1.Text);
              using (SqlDataReader dr = cmd.ExecuteReader())
              {
                   while (dr.Read())
                   {
                        label3.Text = dr.GetSqlValue(0).ToString();
                        results = dr.GetValue(0).ToString();
                        //MessageBox.Show(dr.GetValue(0).ToString());
                        //MessageBox.Show(results);
                    }
                    MessageBox.Show(results);
              }
         }
    } 
}

回答1:


That's correct.
When you exit from the while loop the DataReader has reached the end of the loaded data and thus cannot be used to get the value of a non-existant current record.

The Read method advances the SqlDataReader (dr) to the next record and it returns true if there are more rows, otherwise false.

If you have only one record you could use the results variable in this way

MessageBox.Show(results);

Now, this will work because you have a TOP 1 in your sql statement, but, if you have more than one record, it will show only the value of the last record.

Also as noted by marc_s in its comment, if your table is empty, your code doesn't fall inside the while loop, so probably you could initialize the results variable with a message like:

 results = "No data found";

EDIT: Seeing your comment below then you should change your code in this way

.....
// Use parameters **ALWAYS** -- **NEVER** cancatenate/substitute strings 
string query = "select stationipaddress from station where stationname = @name";
using (SqlCommand cmd = new SqlCommand(query, cs))
{
    // Add the parameter and set its value -- 
    cmd.Parameters.AddWithValue("@name", textBox1.Text);
    using (SqlDataReader dr = cmd.ExecuteReader())
    {

        while (dr.Read())
        {
            label3.Text = dr.GetSqlValue(0).ToString();
            results = dr.GetValue(0).ToString();
        }
    }
}
.....



回答2:


I ran into a similar issue trying to get a GUID I knew was there - I could run the same SQL directly in SQL Management Studio and get my result. So instead of trying to bring it back as a GUID (it was saved in a char(35) field, even though it really was a GUID!), I brought it back as a string, instead:

        SqlConnection sqlConn = null;
        string projId = String.Empty;
        string queryString = "SELECT * FROM project WHERE project_name='My Project'";

        try
        {
            sqlConn = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand(queryString, sqlConn);
            sqlConn.Open();

            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    projId = reader.GetSqlValue(0).ToString();   // <-- safest way I found to get the first column's parameter -- increment the index if it is another column in your result
                }                    
            }
            reader.Close();
            sqlConn.Close();
            return projId;                
        }
        catch (SqlException ex)
        {                
            // handle error
            return projId;
        }
        catch (Exception ex)
        {
            // handle error
            return projId;
        }
        finally
        {
            sqlConn.Close();
        }


来源:https://stackoverflow.com/questions/13635366/sql-data-reader-invalid-attempt-to-read-when-no-data-is-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!