[英]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.