如何在MySQL中保存确切的日期时间
我有一个VB.Net项目,我想在我的MSQL数据库中保存确切的日期时间。但我无法抓住时间和日期。如何在MySQL中保存确切的日期时间
预期的行为:在DB 2012年12月3日1时03分23秒
当前的行为:在DB 2012年12月3日00:00:00
代码段下面:
Dim temp = System.DateTime.Now
Code(temp)
Public Sub Code(ByVal dte As DateTime)
Dim strSQl As String = String.Format("Update tblTenant Set dte = '{0}' blablalbla", dte)
Me._Inst.execSQL(strSQl)
End Sub
EDIT在DB中的列类型是DATETIME
我不确定您的execSQL()
方法是如何构建的,但将可变数据直接替换为SQL查询字符串并不正常,或者完全可以。这是让你的程序被黑客攻击的好方法。相反,您需要一种机制来分别接受数据并将其发送到服务器。这通常看起来是这样的:
Public Sub execSQL(ByVal SQL As String, Optional ByVal ParamArray QueryParameters() As MySqlParameter)
Using cn As New MySqlConnection("connection string here"), _
cmd As New MySqlCommand(SQL, cn)
If QueryParameters IsNot Nothing Then
For Each p As MySqlParameter In QueryParameters
'This does NOT EVER do string manipulation to set the data into the query
' Instead, it's sent to the server in a separate data section, where the variables are setup.
' In this way, data stays separate from code, and any possibility of sql injection is prevented.
cmd.Parameters.Add(p)
Next
End If
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
然后调用它像这样:
Public Sub Code(ByVal dte As DateTime)
Dim strSQl As String = "Update tblTenant Set dte = @dte blablalbla"
Dim dteParam As New MySqlParameter("@dte", MySqlDbType.DateTime)
dteParam.Value = dte
Me._Inst.execSQL(strSQl, dteParam)
End Sub
我见过很多情况下,切换到查询参数也是固定的一个棘手的格式或语法问题,所以我相信在这里使用查询参数很可能会解决引发问题的问题。
您的sql列类型是date(您说不是)或者您没有将完整日期和时间传递给查询。
仔细检查sql列的类型。
然后使用中间字符串调试您的Code
方法以保存日期时间。检查它是否有时间。
Public Sub Code(ByVal dte As DateTime)
Dim dateString = dte.ToString("MM-dd-yyyy hh:mm:ss")
Dim strSQl As String = String.Format("Update tblTenant Set dte = '{0}' blablalbla", dateString)
End Sub
现在,如果你在数据库中正确的类型,查询其实
更新tblTenant设置DTE = '04 -21-2017 11:04 :41'blablalbla
但你仍然没有看到数据库中的时间,你有不同的问题。
我们是否需要在日期时间内放置单引号? – Unbreakable
@坚不可摧当然。最好的办法是在发送到服务器之前查看最终的查询字符串。更好的是,如果可以的话,在SSMS中执行该查询。 – djv
什么是列类型? –
这是疯狂的容易受到SQL注入攻击。 –
使用SQL参数将'DateTime'作为'DateTime'传递。该代码传递文本并让DB提供者解决问题。 – Plutonix