我收到此错误:
无法将MySQL日期/时间值转换为System.DateTime
而我正在尝试从MySQL数据库中获取数据。我的MySQL数据库中有date数据类型。但是在将其检索到我的数据表中时,它会得到上面的错误。
我怎样才能解决这个问题?
如果我谷歌“无法将MySQL日期/时间值转换为System.DateTime”,我看到许多引用从Visual Studio访问MySQL的问题。这是你的背景吗?
一个解决方案建议:
这不是一个错误,而是预期的行为。请检查连接选项下的手动并将“允许零日期时间”设置为true,如附加图片所示,错误将消失。
在Stimulsoft报告中将此参数添加到连接字符串(右键单击datasource-> edit)
Convert Zero Datetime=True;
您必须将Convert Zero Datetime=True
添加到您的连接字符串,例如:
server=localhost;User Id=root;password=mautauaja;Persist Security Info=True;database=test;Convert Zero Datetime=True
我添加了Convert Zero Datetime=True
和Allow Zero Datetime=True
,它工作正常
将日期时间值作为字符串向下拉并执行DateTime.ParseExact(value, "ddd MMM dd hh:mm:ss yyyy", culture, styles);
您只需要为从数据库返回的日期设置日期格式。最有可能的是yyyy-MM-dd HH:mm:ss
。至少对我而言。
点击这里查看有关DateTime.ParseExact
的更多信息
让MySql将你的unix时间戳转换为字符串。使用mysql函数FROM_UNIXTIME(113283901)
我也遇到了同样的问题,并获得列名称及其类型。然后从表名转换(col_Name作为Char)。从这个方面我得到的问题是'0000-00-00 00:00:00'然后我更新作为有效的日期和时间错误离开我的情况。
您可以使应用程序与MySql使用的日期和时间完全兼容。当应用程序在运行时运行时提供此代码。首先转到应用程序事件。在工具列表中
这将打开一个新文件。此文件包含在应用程序启动时使用的代码。
将此代码写入该新文件中:
Partial Friend Class MyApplication
Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
My.Application.ChangeCulture("en")
My.Application.ChangeUICulture("en")
My.Application.Culture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd"
My.Application.Culture.DateTimeFormat.LongDatePattern = "yyyy-MM-dd"
My.Application.Culture.DateTimeFormat.LongTimePattern = "HH:mm:ss"
My.Application.Culture.DateTimeFormat.ShortTimePattern = "HH:mm:ss"
End Sub
End Class
您可以使用IsValidDateTime
对象的MySqlDateTime
属性来帮助您确定是否可以将对象强制转换为DateTime
,而不是更改连接字符串。
我有一个场景,我试图从“UpdateTime”列加载数据,该列仅在行更新时显式设置(而不是始终设置的InsertedTime)。对于这种情况,我使用MySqlDataReader.GetMySqlDateTime
方法,如下所示:
using (MySqlDataReader reader = await MySqlHelper.ExecuteReaderAsync(...))
{
if (await reader.ReadAsync())
{
DateTime? updateTime = reader.GetMySqlDateTime("UpdateTime").IsValidDateTime ? (DateTime?)reader["UpdateTime"] : null;
}
}
如果“allow zero datetime = true”不起作用,请使用以下解决方案: -
将此添加到您的连接字符串:“allow zero datetime = no” - 这使得类型转换工作完美。