1
int n =Count("SELECT COUNT(*) FROM information_schema.SCHEMATA");; //return 6

TreeNode[] db_name = new TreeNode[n];
MySqlCommand cmd = new MySqlCommand("show databases", connection);
MySqlDataReader dataReader = cmd.ExecuteReader();

for(i=0;i<n;i++)
{
    dataReader.Read();
    db_name[i] =  new TreeNode(dataReader[i].ToString());
}  

Why do I get IndexOutOfRangeException was unhandled,Index was outside the bounds of the array? If the Count() funciont return 6 that means there are 6 rows so 6 fields [0][1][2][3][4][5] I put a breakpoint in the for loop and I get the error at the second loop, when i=1. How can I fix that? I can't see the error. Thanks in advance.

Kevin Brechbühl
  • 4,717
  • 3
  • 24
  • 47
Bruce Rox
  • 21
  • 5
  • How does the first line compile at all? – Thorsten Dittmar Feb 11 '14 at 13:25
  • 2
    Your code is based on a wrong assumption that `show databases` command would return a single column for each row in `information_schema.SCHEMATA`. This assumption is incorrect - the `information_schema.SCHEMATA` has a row for each database schema, not for each column returned by `show databases`. – Sergey Kalinichenko Feb 11 '14 at 13:30

2 Answers2

2

The call to dataReader.Read() advances to the next available record.

When you call dataReader[i], you're probably trying to get a column that doesn't exist in your returned data. On the first iteration, dataReader[i] is trying to get the first column, but then on the second iteration it's just trying to get the second column, then third, etc. You're probably not returning 6 columns, so that's going to throw an exception.

You could try something like this instead, assuming that each record is just a string:

for(i=0; i<n; i++)
{
    dataReader.Read();
    db_name[i] =  new TreeNode(dataReader.GetString(0));

          // or use dataReader[0].ToString(), but don't change the index of 0
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
1

Please try the following.

int i=0;
if (dataReader.HasRows)
{
    while (dataReader.Read())
    {
        db_name[i] =  new TreeNode(dataReader.GetString(0));          
    }
    i++;
}
Christos
  • 53,228
  • 8
  • 76
  • 108
  • 1
    Just because it isn't an array doesn't mean you can't access the data reader like one. If it didn't have the indexer the program wouldn't compile. MySqlDataReader probably implements [IDataReader](http://msdn.microsoft.com/en-us/library/system.data.idatareader%28v=vs.100%29.aspx) which has array-like access to the columns. – Dirk Feb 11 '14 at 13:28
  • @Drik Oh, I didn't know it. Thanks, Dirk – Christos Feb 11 '14 at 13:29