繁体   English   中英

vb.net,mysql插入日期

[英]vb.net, mysql inserting dates

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

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()

结束子

通常,使用参数化查询可以完全避免这些问题(以及其他问题)

这是一个示例,您需要为每个参数修复正确的数据类型( 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM