2017-04-21 25 views
0

我有一个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

+0

什么是列类型? –

+2

这是疯狂的容易受到SQL注入攻击。 –

+1

使用SQL参数将'DateTime'作为'DateTime'传递。该代码传递文本并让DB提供者解决问题。 – Plutonix

回答

1

我不确定您的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 

我见过很多情况下,切换到查询参数也是固定的一个棘手的格式或语法问题,所以我相信在这里使用查询参数很可能会解决引发问题的问题。

+0

您是否建议OP在查询中没有时间地恶意注入日期? – djv

+0

我了解sql注入方面,但严重的是,有参数化查询比字符串更好地保存日期​​+时间的情况吗? – djv

+0

@djv我见过很多情况下切换到参数固定一些奇怪的格式问题,如服务器运行与意外的区域设置。参数通常也更快,而且它们只是处理这种情况的正确方法。 –

-1

您的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 

enter image description here

现在,如果你在数据库中正确的类型,查询其实

更新tblTenant设置DTE = '04 -21-2017 11:04 :41'blablalbla

但你仍然没有看到数据库中的时间,你有不同的问题。

+0

我们是否需要在日期时间内放置单引号? – Unbreakable

+0

@坚不可摧当然。最好的办法是在发送到服务器之前查看最终的查询字符串。更好的是,如果可以的话,在SSMS中执行该查询。 – djv

相关问题