我使用 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
文本框的文本属性嵌入到 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 方法从文本中提取有效的日期时间对象
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 在其评论中所说,有很多最佳实践需要应用于您的代码
- 不要为连接、适配器和 其他托管类。使用后需要立即弗雷德 并在您再次需要时重建
- 诸如连接、适配器以及最终的 DataReader 之类的对象 实现一次性接口(interface)。这意味着您应该 将它们包含在 using 语句中,以便在不使用时销毁它们 不再需要它们
- 不要在您的方法中对连接字符串进行硬编码。如果你想 分发您的应用程序,您需要在各处更改该字符串 (除非你的目标电脑有相同的路径)使用app.Config (web.Config) 和用于检索它的 ConfigurationManager 类
关于sql - 在 VB.Net 中使用 SQL 连接到 Access 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28856564/