如何使用datetimepicker
中的VB.NET
将数据插入数据库?我尝试使用以下方法转换它:
我在Format(name_of_the_datetimepicker.Value, "yyyy-MM-dd")
声明中SQL
,但我不知道哪里出错了。
这是我的代码:
Imports MySql.Data.MySqlClient
Public Class frmMain
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Not conn Is Nothing Then
conn.Close()
End If
conn = New MySqlConnection("Data Source=" & Server & ";user id=" & UserName & ";password=" & PassWord & ";database=" & DatabaseName & ";")
Try
conn.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
Dim cmdSave As MySqlCommand
Dim sql As String
sql = "INSERT INTO (rental_date, inventory_id, customer_id, return_date, staff_id) VALUES ('" & Format(dt_picker_rental_date.Value, "yyyy-MM-dd") & "', '" & txt_inventory_id.Text & "', '" & txt_customer_id.Text & "', '" & Format(dt_picker_return_date.Value, "yyyy-MM-dd") & "', '" & txt_staff_id.Text & "')"
Try
cmdSave = New MySqlCommand(sql, conn)
cmdSave.ExecuteNonQuery()
MsgBox("Success!")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
答案 0 :(得分:1)
请勿使用字符串连接将数据插入SQL代码中。总是使用参数。参数以二进制形式维护所有数据,因此格式绝不是问题。更重要的是,您可以免受SQL注入。使用日期,可能如下所示:
Dim command As New MySqlCommand("INSERT INTO MyTable (DateColumn) VALUES (@DateColumn)", connection)
command.Parameters.AddWithValue("@DateColumn", myDateTimePicker.Value)
如果您只想插入没有时间的日期,请使用Value.Date
而不只是Value
。
有关ADO.NET参数的更多信息:
http://jmcilhinney.blogspot.com.au/2009/08/using-parameters-in-adonet.html
答案 1 :(得分:0)
试试这个。它可能对你有帮助。
cmd.Parameters.Add(" date",OleDbType.DBDate).Value = DateTimePicker1.Value