November 01, 2011

Saving System.DateTime values into MySQL

When trying to save a DateTime value in a MySQL database, or loading MySQL date values into a DateTime object, you normally get an exception saying "Unable to convert MySQL date/time to System.DateTime".

One solution to this problem is to use the mysql connector library for .NET, which can be downloaded from here. Using the mysql connector, we can save our DateTime value into a MySqlDateTime datatype and the database will accept this value. Care should be taken if the MySQL date value is 0000-00-00 00:00:00 since this is outside the range of a DateTime object

Another solution is to format the DateTime into a string that MySQL recognizes.

For example:


string sql = "INSERT INTO mytable (text, created) " +
             "VALUES (@text, @created)";
string text = "Hello World";
DateTime created = DateTime.Now;

MySqlCommand cmd = new MySqlCommand(sql, GetOpenConnection());
cmd.Parameters.AddWithValue("@text", text);
cmd.Parameters.AddWithValue("@created", created.ToString("yyyy-MM-dd hh:mm:ss"));

This way MySQL accepts the date value.

No comments:

Post a Comment