Reading with MySqlDataReader

假如想象 提交于 2019-12-11 23:30:02

问题


Hello I'm having problem to read with MySqlDataReader. I've tried to change while() to if() and it worked then. So I'm doing something wrong with while (Reader.Read()). Thanks for answer. ( The other question today is fixed, someone that commented helped me xd )

using (MySqlCommand cmd = new MySqlCommand
      ("SELECT * FROM `citationer`",  mysqlCon))
{
    try
    {
        MySqlDataReader Reader = cmd.ExecuteReader();
        while (Reader.Read()) // this part is wrong somehow
        {
            citationstexter.Add(Reader.GetString(loopReading)); // this works
            loopReading++; // this works
        }
        Reader.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

回答1:


Your problem is the use of the loopReading parameter to GetString. This parameter should be the zero-based column ordinal (the column number), but you're incrementing it for every row you read.

See here for more info: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getstring.aspx

You should use 0 for the first column of your citationer table, 1 for the second column, etc.

Also, it's good practice to use

  using(MySqlDataReader Reader = cmd.ExecuteReader()) 
  {
    ...
  }

just like you did for the mySqlCommand object to save a memory leak (but this is not your problem.)



来源:https://stackoverflow.com/questions/5606643/reading-with-mysqldatareader

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