我希望从“日期”列的日期是今天的日期获取所有字段。
我的代码是
Dim today As Date = DateTime.Now
vandaag = Format(today, "dd/MM/yyyy")
"select * from tblPatients where PatientDate =" & today & ""
是的,有人能帮帮我吗?这是为了学校...
答案 0 :(得分:2)
永远不要使用字符串连接来构建SQL命令以传递给数据库引擎
使用参数,可以避免文本解析中的问题(日期,带有特殊字符的字符串等),但最重要的是,您要避免使用Sql Injection Attacks。
这是一种习惯,每个与数据库一起工作的开发人员都应该尽快获得
因此,假设您已经构建并打开了OleDbConnection,您可以编写
Dim strSql As String = "select * from tblPatients where PatientDate = ?dt"
Using dadapter = New OleDbDataAdapter()
dadapter.SelectCommand = New OleDbCommand(strSql, con)
dadapter.SelectCommand.Parameters.AddWithValue("?dt", DateTime.Today)
Dim dset As DataSet = New DataSet()
dadapter.Fill(dset, "Books")
End Using
另请注意Using statement,这是另一个好习惯
Using
将处理从内存中处理OleDbConnection和OleDbDataAdapter等对象,从而释放对象使用的所有系统资源
答案 1 :(得分:2)
实际上,您的查询中根本不需要参数:
SELECT * FROM tblPatients WHERE PatientDate = DATE()
如果PatientDate是合并日期时间,您可以使用:
SELECT * FROM tblPatients WHERE PatientDate BETWEEN DATE() AND DATEADD('d', 1, DATE())
Date() - Function的时间部分为0:00,因此这将为您提供当天的正确结果。
答案 2 :(得分:0)
Dim strSql As String = "select * from tblPatients where PatientDate =#" & today & "#"
Dim dadapter As OleDbDataAdapter
dadapter = New OleDbDataAdapter()
dadapter.SelectCommand = New OleDbCommand(strSql, con)
Dim dset As DataSet = New DataSet()
dadapter.Fill(dset, "Books")
答案 3 :(得分:0)
使用DATEADD
和DATEDIFF
功能删除日期之后的时间:
Dim dayPart As String = Chr(34) & "d" & Chr(34) 'Chr(34) = ", resulting string is "d" (enclosed in quotes)
Dim query As String = "SELECT * FROM tblPatients"
'Declared as separate variables for better readability
Dim patientDate As String = "DATEADD(" & dayPart & ", DATEDIFF(" & dayPart & ", 0, PatientDate), 0)"
Dim todaysDate As String = "DATEADD(" & dayPart & ", DATEDIFF(" & dayPart & ", 0, Now());"
'patientDate = 'DATEADD("d", DATEDIFF("d", 0, PatientDate), 0)' which is the patientDate, stripped of a timevalue
'todaysDate = 'DATEADD("d", DATEDIFF("d", 0, Now()), 0)' which is today's date, stripped of a timevalue
'This works because:
'DATEDIFF("d", 0, PatientDate) returns the number of days that have passed since the "zero" date and strips the time component
'DATEADD("d", DATEDIFF("d", 0, PatientDate), 0) adds the DATEDIFF calculation to the "zero" date returning a date
'equal to PatientDate with no time component.
'This same principle is applied to the 'Now()' function to get today's date with no time component.
'
'Now that patientDate can equal today's date (because the time components have been stripped away), we can affix the where clause
query &= " WHERE " & patientDate & " = " & todaysDate
'and run the query
答案 4 :(得分:0)
试试这个
"select * from tblPatients where PatientDate =" & Now() & ""
或
"select * from tblPatients where PatientDate =" & Now().Date() & ""