Note that there are some explanatory texts on larger screens.

plurals
  1. POGetting exception: Invalid attempt to read when reader is closed
    primarykey
    data
    text
    <p>I am attempting to read a MySQL database from my C# project using the MySQL drivers for .net off the MySQL site.</p> <p>Though I did a bit of research on this (including <a href="https://stackoverflow.com/questions/5516914/invalid-attempt-to-read-when-reader-is-closed">this</a>), I am still flummoxed why this is happening. I later ran a spike and I still get the same error. (Prior to running this I populated the database with some default values.) Here's the spike code in toto.</p> <pre><code>class Program { static void Main (string[] args) { Console.WriteLine (GetUserAge ("john")); // o/p's -1 } static int GetUserAge (string username) { string sql = "select age from users where name=@username"; int val = -1; try { using (MySqlConnection cnn = GetConnectionForReading ()) { cnn.Open (); MySqlCommand myCommand = new MySqlCommand (sql, cnn); myCommand.Parameters.AddWithValue ("@username", username); using (MySqlDataReader reader = myCommand.ExecuteReader ()) { DataTable dt = new DataTable (); dt.Load (reader); if (reader.Read ()) { val = reader.GetInt32 (0); } } } } catch (Exception ex) { Console.WriteLine (ex.Message); } finally { } return val; } private static MySqlConnection GetConnectionForReading () { string conStr = "Data Source=localhost;Database=MyTestDB;User ID=testuser;Password=password"; return new MySqlConnection (conStr); } } </code></pre> <p>The code above gives me the exception: "Invalid attempt to Read when reader is closed."</p> <p>Later I modified the if-condition like so:</p> <pre><code>if (reader.HasRows &amp;&amp; reader.Read ()) { val = reader.GetInt32 (0); } </code></pre> <p>And now the o/p is -1. (The data's in there in the table.) If for some reason the result set had zero rows, the reader should not have got into the if-block in the first place. I mean, the whole point of the Read() method is to check if there are any rows in the result set in the first place.</p> <p>At my wit's end here... just cannot figure out where I'm going wrong.</p> <p>Thank you for your help! :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload