我想在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
结束班
答案 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)