2

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!

4

2 回答 2

2

You need to check for the DBNull before you call GetString(). See this answer.

if (!myReader.IsDBNull(i))
    sb.Append(myReader.GetString(i));
于 2012-04-10T03:07:45.293 回答
1

Generally, you need to pay attention to values of nullable columns. DB signals that the returned value is null by returning a special object called DBNull. You cannot cast it to string or anything else, so your code should check for null by using IsDBNull like this:

if (!myReader.IsDBNull(i)) {
    sb.Append(myReader.GetString(i) + " ");
}
于 2012-04-10T03:07:47.313 回答