我使用Access作为备份数据存储(我知道为什么不正确使用MySQL吗?)。无论如何,要克服这一点,我想使用SQL在数据库中搜索预订日期。我可以查询今天的日期,但是我想用某种方式输入日期,然后根据该日期查找结果。到目前为止,我的代码是这样的:
Public Class Bookings
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Bookings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = "PROVIDER=Microsoft.Jet.OleDB.4.0;"
dbSource = "Data Source = C:\Users\wm\Desktop\MAdams\Karting2000DB.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT * FROM tblBookings WHERE BookingDate = txtDate.Text"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "AddressBook")
MsgBox("Database is now open")
con.Close()
MsgBox("Database is now closed")
txtBookingNumber.Text = ds.Tables("AddressBook").Rows(0).Item("ID")
txtCustID.Text = ds.Tables("AddressBook").Rows(0).Item("CustomerID")
End Sub
End Class
我对此很陌生,越简单越好!
非常感谢
您不能将文本txtDate
框的text属性嵌入sql字符串中,并希望将其转换为正确的值。
您需要使用参数化查询
sql = "SELECT * FROM tblBookings WHERE BookingDate = @date"
da = New OleDb.OleDbDataAdapter(sql, con)
da.SelectCommand.Parameters.Add("@date", OleDbType.Date).Value = Convert.ToDateTime(txtDate.Text)
da.Fill(ds, "AddressBook")
此方法要求您的用户在文本框中键入有效日期。如果不确定日期是否正确,则需要使用TryParse方法从文本中提取有效的datetime对象。
Dim bookDate as DateTime
if Not DateTime.TryParse(txtDate.Text, bookDate) then
MessageBox.Show("Not a valid date")
else
..... the code above with the bookDate passed as parameter value.
正如@Plutonix在其评论中所说,有许多最佳实践需要应用于您的代码
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句