Private Sub Search_Record()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT * FROM [Data]"
Dim d1, d2 As String
d1 = Format(Me.dtpDOB1.Value, "dd/MM/yyyy")
d2 = Format(Me.dtpDOB2.Value, "dd/MM/yyyy")
Dim betchar As String = " where "
Dim Orkey As String = " and"
the date between d1 and d2 not working fine
If Not dtpDOB1.Text = " " Then
If Not dtpDOB2.Text = " " Then
If Not d1 = "" Then sSQL = sSQL & betchar + " date = #" & d1 & "#"
Else
If Not d1 = "" Then sSQL = sSQL & betchar + " date Between #" & d1 & "# AND #" & d2 & "#"
End If
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.DataGridView1.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Catch ex As Exception
MsgBox(ErrorToString)
Finally
conn.Close()
End Try
End Sub
答案 0 :(得分:0)
在每个已知的数据库系统中,单词DATE通常是保留关键字。 如果你真的想要使用它(一个非常糟糕的选择),那么在该词周围使用方括号
If Not d1 = "" Then sSQL = sSQL & betchar + " [date] ...
说我真的建议你开始使用参数化查询来提高查询的可读性,避免任何Sql注入的可能性
Dim prm = new List(Of OleDbParameter)()
If Not dtpDOB1.Text = " " Then
If Not dtpDOB2.Text = " " Then
If Not d1 = "" Then
sSQL = sSQL & " WHERE [date] = ?"
Dim p = new OleDbParameter()
p.ParameterName = "d1"
p.OleDbType = OleDbType.Date
p.Value = Me.dtpDOB1.Value
prm.Add(p)
End If
Else
If Not d1 = "" Then
sSQL = sSQL & " WHERE [date] >= ? AND [date] <= ?"
Dim p = new OleDbParameter()
p.ParameterName = "d1"
p.OleDbType = OleDbType.Date
p.Value = Me.dtpDOB1.Value
prm.Add(p)
p = new OleDbParameter()
p.ParameterName = "d2"
p.OleDbType = OleDbType.Date
p.Value = Me.dtpDOB2.Value
prm.Add(p)
End If
End If
End If
cmd.CommandText = sSQL
cmd.Parameters.AddRange(prm.ToArray())
da.SelectCommand = cmd
da.Fill(dt)
....