Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySqlConversionException when accessing DateTime field from DataReader

I have a C# application over MySql, using MySQL Connector; I'm trying to make a DataReader request, the query executes fine, however, when trying to access a DateTime field, i'm getting MySqlConversionException {"Unable to convert MySQL date/time value to System.DateTime"}

this is the prototype

if (dr != null && !dr.Read()) return;

sesion.Id = Convert.ToInt32(dr["id"]);
sesion.Usuario = Convert.ToInt32(dr["usuario"]);
sesion.Estado = Convert.ToByte(dr["estado"]);
// doesn't work
sesion.FchCreacion = Convert.ToDateTime(dr["fch_creacion"]);

Any suggestions? Thanks in advance

like image 480
Jhonny D. Cano -Leftware- Avatar asked Apr 02 '09 15:04

Jhonny D. Cano -Leftware-


2 Answers

This error sometimes occurs if you have zero datetime values in your MySQL database (00/00/0000 00:00). Try adding this to the end of your connection string:

Allow Zero Datetime=true
like image 144
David M Avatar answered Oct 25 '22 19:10

David M


There are a few potential gotchas when converting between MySQL dates/times and .NET DateTimes, but there's a useful section in the MySQL documentation with advice on how to handle the issues.

like image 27
LukeH Avatar answered Oct 25 '22 19:10

LukeH