问题
I am working on a C# project and I am facing an issue. The program allows the user to connect to a MySQL database and retrieve information from each selected table and write the data out to a file. The problem is because I have no idea what the schema is going to be like or what values its going to contain.
If the timestamp column contains the date 0000-00-00 00:00:00 I get the conversion error and no matter what I try it never works. I've tried converting to a string I've tried converting to a DateTime but I always get the error.
Below is how I am currently trying to get the data:
using (ConnectMySQLDB db = new ConnectMySQLDB(databaseSettings))
{
string query = string.Format("SELECT * FROM {0}.{1}", database, table);
Console.WriteLine("Query: {0}", query);
using (MySqlCommand cmd = new MySqlCommand(query, db.conn))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
int i = 1;
while (reader.Read())
{
Console.WriteLine("ID: {0}", i);
fieldsAndValues = new Dictionary<string, string>();
foreach (ColumnDataTypes fieldAndType in fieldsAndTypes)
{
Console.WriteLine("Column: {0} Type: {1}", fieldAndType.field, fieldAndType.dataType);
string formattedValue = "";
if (fieldAndType.dataType == "timestamp")
{
DateTime date = DateTime.Parse(reader.GetDateTime(fieldAndType.field).ToString());
formattedValue = date.ToString("yyyyMMdd");
}
else
{
formattedValue = getDBFormattedValue(reader.GetString(fieldAndType.field), fieldAndType.dataType);
fieldsAndValues.Add(fieldAndType.field, formattedValue);
}
}
rows.Add(fieldsAndValues);
i++;
}
}
}
}
I also have added the allow zero date and convertzerodate to null option in the connector string as follows:
connString = "server=" + server + ";uid=" + username + ";pwd=" + password + ";port=" + port + ";Allow Zero Datetime=true;zeroDateTimeBehavior=convertToNull;Convert Zero Datetime=true";
回答1:
Looking at this documentation, it looks like you're specifying two contradictory options (AllowZeroDateTime=true and ConvertZeroDateTime=true) and one which appears not to be listed (ZeroDateTimeBehavior=ConvertToNull).
I suggest that unless you have actual data which is DateTime.MinValue which you don't want to mix up with the "zero" value, you just specify ConvertZeroDateTime=true and detect if the result is DateTime.MinValue. You definitely shouldn't call reader.GetDateTime(), then convert the result to a string, and then back to a DateTime - you should avoid string conversions as far as you can, as they can mess things up for you pretty easily.
It's not really clear what string value you want for these "zero" values, but you should be able to special-case them with DateTime.MinValue fairly easily. Personally I'd actually try to keep the data in its "native" form as much as possible rather than converting everything to strings, but that's a different battle.
来源:https://stackoverflow.com/questions/15982137/unable-to-convert-mysql-datetime-to-system-datetime-with-0000-00-00-000000-val