当我开始表单"无法将mysql日期/时间值转换为system.datetime"
时,我一直收到错误这是我的代码
Private Sub Add_Button1(sender As Object, e As EventArgs) Handles Add_Button.Click
MySqlConn = New MySqlConnection
MySqlConn.ConnectionString = "Server = Localhost; database = apartmentdb; user id = root; Password = "
Dim Reader As MySqlDataReader
Try
MySqlConn.Open()
Dim Query As String
Query = "Insert into Apartmentdb.Bookings(Apartment_ID, Client_ID, Booking_start_Date, Booking_end_Date, Total_Days, Price_per_Week, Total_Price) Values ('" & TextBox5.Text & "', '" & TextBox4.Text & "', '" & DateTimePicker4.Value & "' , '" & DateTimePicker3.Value & "' ,'" & TextBox3.Text & "', '" & TextBox2.Text & "', '" & TextBox1.Text & "')"
Command = New MySqlCommand(Query, MySqlConn)
Reader = Command.ExecuteReader
MessageBox.Show("Data Saved")
MySqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
Call GridView_load()
End Sub
答案 0 :(得分:0)
不是VB人,但这应该是一个开始。
Private Sub Add_Button1(sender As Object, e As EventArgs) Handles Add_Button.Click
Using MySqlConn as New MySqlConnection("Server = Localhost; database = apartmentdb; user id = root; Password = ")
Dim Query As String
Query = "Insert into Apartmentdb.Bookings(Apartment_ID, Client_ID, Booking_start_Date, Booking_end_Date, Total_Days, Price_per_Week, Total_Price)
Values (@Apartment_ID,@Client_ID,@Start_Date,@End_Date,@Total_Days,@Price_Per_week, @Total_Price)"
MySqlConn.Open()
Using MyCommand = New MySqlCommand(Query, MySqlConn)
MyCommand.Parameters.AddWithValue("@ApartmentID",TextBox5.Text)
MyCommand.Parameters.AddWithValue("@Client_ID", TextBox4.Text)
// and so on.
MyCommand.ExecuteNonQuery
MessageBox.Show("Data Saved")
End Using
End Using
Call GridView_load()
End Sub
注意捕获异常是没有意义的,除非这个函数根本不重要。您应该只捕获可以处理的异常。 使用消除了最后尝试的需要,关闭东西。范围内的一切,它与连接池非常有效。 参数化查询不仅可以阻止注入攻击,而且非常适合本地化数据,例如数字和日期格式。
当您将转换后的Picker.Value编码为一个字符串时,您的问题几乎可以肯定,它是一个字符串,您的sql server不知道如何处理。即使它已经过去了。你可以得到旧的8/6/2015是6月8日或8月6日的问题。
剥离时间是一个稍微不同的问题取决于您的数据库,但如果您想确保其0(午夜),那么SomePicker.Value.Date
将执行该操作。