Wednesday, April 25, 2012

C# - Can't get column types from MySQL

Here's some code:



OdbcConnection connection = new OdbcConnection(@"DRIVER={MySQL ODBC 5.1 Driver};SERVER=" + ip + ";DATABASE=db_name;USER=user;PASSWORD=" + dbPw + ";");
connection.Open();

string queryString = query;
OdbcCommand command = new OdbcCommand(queryString);

command.Connection = connection;
OdbcDataReader myReader = command.ExecuteReader();
int fieldsN = myReader.FieldCount;

StringBuilder sb = new StringBuilder();

while (myReader.Read())
{
for (int i = 0; i < fieldsN; i++ )
{
sb.Append(myReader.GetString(i) + " ");
}
sb.Append(", ");
}

connection.Close();

//Console.WriteLine(sb.ToString());


This code works fine with queries like "SELECT * FROM some_table" or "SELECT (something, something_else) FROM some_table."



However it fails when I use "SHOW COLUMNS FROM some_table."



Here's the error I get:




Unable to cast object of type 'System.DBNull' to type 'System.String'.




This error happens somewhere in the myReader.GetString() line.



I've tried creating an if statement that checks if myReader.GetString(i) is System.DBNull to no avail. Whatever I do it always errors out. I don't understand what is going on.



Thanks for any help!





No comments:

Post a Comment