【问题标题】:vb.net, mysql inserting datesvb.net,mysql插入日期
【发布时间】:2015-03-07 16:43:29
【问题描述】:

嗨,我试图将 vb.net 中的日期插入我的 sql 数据库,结果一直显示为 00-00-00 我使用日期时间选择器来获取格式化为短格式的日期

Public Sub NewAppointment()

    SQLCommand.Connection = SQLconnection
    SQLCommand.CommandText = "INSERT INTO " & _
appointment(TattooID,Date,Time,Length,Deposit,Cost) VALUES"& _
 ('" & _Tattoo.ID & "','"& _
  " & AppDate.Date & "','" & _
  " & AppTime & "','" & _
  " & AppLength.ToString & "','" & _
  " & AppDespoit & "','" & AppCost & "');"


  SQLCommand.CommandType = CommandType.TableDirect

        Try
            SQLconnection.Open()
            SQLCommand.ExecuteNonQuery()
            SQLconnection.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        SQLconnection.Dispose()

结束子

【问题讨论】:

    标签: mysql database vb.net datetime


    【解决方案1】:

    像往常一样,通过参数化查询完全避免了这些问题(以及其他问题)

    这是一个示例,您需要为每个参数修复正确的数据类型(MySqlDbType)以匹配您的数据表字段的数据类型

    SQLCommand.Connection = SQLconnection
    SQLCommand.CommandText = "INSERT INTO " & _
        " appointment(TattooID,Date,Time,Length,Deposit,Cost) VALUES "& _
        " (@id, @appDate, @AppTime, @AppLength,@AppDespoit,@AppCost);"
    SQLCommand.Parameters.Add("@id", MySqlDbType.VarChar).Value = _Tattoo.ID
    SQLCommand.Parameters.Add("@AppDate", MySqlDbType.Date).Value = AppDate.Date 
    SQLCommand.Parameters.Add("@AppTime", MySqlDbType.Date).Value = AppTime
    SQLCommand.Parameters.Add("@AppLength", MySqlDbType.VarChar).Value = AppLength
    SQLCommand.Parameters.Add("@AppDespoit", MySqlDbType.VarChar).Value = AppDespoit 
    SQLCommand.Parameters.Add("@AppCost", MySqlDbType.VarChar).Value = AppCost 
    

    现在,为您的日期字段获取正确值的工作被传递给数据库引擎,该数据库引擎接收日期类型的参数并知道如何从参数中提取值并将其存储在相关字段中。

    请注意您的查询现在如何更具可读性,并且作为额外的好处,您可以避免任何可能的Sql Injection

    【讨论】:

    • 工作,感谢它还纠正了我表中已有的所有数据:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2011-07-29
    相关资源
    最近更新 更多