我想从“日期”列中的日期为今天日期的行中获取所有字段。
我的代码是
Dim today As Date = DateTime.Now
vandaag = Format(today, "dd/MM/yyyy")
"select * from tblPatients where PatientDate =" & today & ""
有人可以帮我吗?是为了上学...
实际上,您的查询中根本不需要参数:
SELECT * FROM tblPatients WHERE PatientDate = DATE()
如果 PatientDate 是组合的日期时间,您可以使用:
SELECT * FROM tblPatients WHERE PatientDate BETWEEN DATE() AND DATEADD('d', 1, DATE())
Date()-Function 的时间部分为 0:00,因此这将为您提供当天的正确结果。
切勿使用字符串连接来构建 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 语句,这是另一个值得遵循的好习惯。
Using
将负责从内存中处理 OleDbConnection 和 OleDbDataAdapter 等对象,从而释放对象使用的所有系统资源
使用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
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")
尝试这个
"select * from tblPatients where PatientDate =" & Now() & ""
或者
"select * from tblPatients where PatientDate =" & Now().Date() & ""