使用VB.NET从Access数据库中检索两个日期之间的数据

时间:2016-06-06 03:21:33

标签: vb.net ms-access datagridview

我想在datagridview中显示数据库中的数据。我在da.Fill(ds, "SAMPLE")收到“数据类型不匹配错误”错误。请看截图。 我的日期格式是datetimepicker和数据库值的“短日期”。

Imports System.Data.OleDb
Public Class Form1
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Recto D Sanchez Jr\Documents\sample.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    MyConn = New OleDbConnection
    MyConn.ConnectionString = connString
    ds = New DataSet
    tables = ds.Tables
    da = New OleDbDataAdapter("Select * from SAMPLE where [LOGDATE] between '" & DateTimePicker1.Text & "' And '" & DateTimePicker2.Text & "'", MyConn)
    da.Fill(ds, "SAMPLE")
    Dim view As New DataView(tables(0))
    source1.DataSource = view
    DataGridView1.DataSource = view
End Sub

结束班

error screenshot

2 个答案:

答案 0 :(得分:1)

由于您的DateTimePicker控件已经处理了正确的DateTime值,您可能会更好地使用参数化查询,如下所示:

MyConn = New OleDbConnection(connString)
Dim cmd As New OleDbCommand("SELECT * FROM [SAMPLE] WHERE [LOGDATE] Between ? And ?", MyConn)
cmd.Parameters.AddWithValue("?", DateTimePicker1.Value.Date)
cmd.Parameters.AddWithValue("?", DateTimePicker2.Value.Date)
da = New OleDbDataAdapter(cmd)
ds = New DataSet
da.Fill(ds, "SAMPLE")

它可以省去处理不同日期格式,分隔日期文字和其他潜在陷阱的麻烦。

答案 1 :(得分:0)

尝试

da = New OleDbDataAdapter("Select * from SAMPLE where [LOGDATE] between #" & DateTimePicker1.Value.ToString("MM/dd/yyyy HH:mm:ss") & "# And #" & DateTimePicker2.Value.ToString("MM/dd/yyyy HH:mm:ss") & "#", MyConn)