MySqlConversionException when accessing DateTime field from DataReader

天大地大妈咪最大 提交于 2020-01-02 04:10:10

问题


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


回答1:


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



回答2:


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.




回答3:


I'd suggest it may be a culture specific error - is the applicaiton on the same server as the DB, and do they have the same culture settings?

Also, is the column definitely a datetime in MySQL?




回答4:


It could also be a DBNull value.



来源:https://stackoverflow.com/questions/710182/mysqlconversionexception-when-accessing-datetime-field-from-datareader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!