我使用datagridview
来显示学生记录..
我想显示按照旅店老板出生日期过滤的记录。
当我使用自定义格式datetimepicker
从dd/mm
选择11/09来搜索数据时,它没有显示任何内容。
如何在忽略年份的同时仅匹配dd / mm来显示所有记录?
这是我的代码:
Try
con = New OleDbConnection(cs)
con.Open()
cmd = New OleDbCommand("SELECT HostelerID as [Hosteler ID],HostelerName as [Hosteler Name],DOB,HostelName as [Hostel Name],RoomNo as [Room No],DateOfJoining as [Date Of Joining],Purpose,FatherName as [Father's Name],MobNo1 as [Mobile No],Phone1 as [Phone No],MotherName as [Mother's Name],MobNo2 as [Mobile No 2],City,Address,Email,ContactNo as [Contact No],InstOfcDetails as [Ins/Ofc Details],Phone2 as [Phone No 2],Agreement,GuardianName as [Guardian Name],GuardianAddress as [Guardian Address],MobNo3 as [Guardian Mobile No],Phone3 as [Guardian Phone No],FixedDeposit as [Fixed Deposit],CompletionDate as [Completion Date],Photo,DocsPic as [Docs Pic] from Hostelers where DOB like #" & DateTimePicker1.Text & "# order by HostelerName", con)
Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim myDataSet As DataSet = New DataSet()
myDA.Fill(myDataSet, "Hostelers")
DataGridView6.DataSource = myDataSet.Tables("Hostelers").DefaultView
con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
答案 0 :(得分:2)
尝试将'where'子句更改为:
" WHERE MONTH(DOB) = " & DateTimePicker1.Value.Month &
" AND DAY(DOB) = " & DateTimePicker1.Value.Day
但是我也强烈建议您使用参数化SQL命令 http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters.aspx
这将阻止SQL注入(http://technet.microsoft.com/en-us/library/ms161953(v=SQL.105).aspx)和其他错误
答案 1 :(得分:2)
“使用自定义格式dd / mm从日期时间选择器中选择11/09来搜索数据”
在Access查询中,您可以要求数据库引擎将Format()
应用于您的DOB
值,然后进行比较。这样做可以用于静态值 '11 / 09' ...
WHERE Format(DOB, 'dd/mm') = '11/09'
为了使其灵活,您可以使用参数查询并提供DateTimePicker1.Text
作为参数值。
WHERE Format(DOB, 'dd/mm') = your_string
答案 2 :(得分:1)
将您的查询更改为以下内容:
cmd = New OleDbCommand("
SELECT HostelerID as [Hosteler ID], HostelerName as [Hosteler Name],
DOB, HostelName as [Hostel Name],
RoomNo as [Room No], DateOfJoining as [Date Of Joining],
Purpose, FatherName as [Father's Name],
MobNo1 as [Mobile No], Phone1 as [Phone No],
MotherName as [Mother's Name], MobNo2 as [Mobile No 2],
City, Address, Email, ContactNo as [Contact No],
InstOfcDetails as [Ins/Ofc Details], Phone2 as [Phone No 2],
Agreement, GuardianName as [Guardian Name],
GuardianAddress as [Guardian Address], MobNo3 as [Guardian Mobile No],
Phone3 as [Guardian Phone No], FixedDeposit as [Fixed Deposit],
CompletionDate as [Completion Date], Photo, DocsPic as [Docs Pic]
FROM Hostelers
WHERE (DatePart(\"M\", DOB) = '" + DateTimePicker1.Value.Date.Month + '")
AND (DatePart(\"D\", DOB) = '" + DateTimePicker1.Value.Date.Day + '"))
ORDER BY HostelerName
")