用日期和时间段之间的记录填充数据网格——使用c#和OLE DB
本文关键字:网格 使用 OLE DB 数据网 填充 时间段 日期 之间 记录 数据 | 更新日期: 2023-09-27 18:10:49
我在过滤两个DateTime值之间的一组数据时遇到困难。
例如:检索所有记录From: 24/04/2013 3:54 PM;至:24/04/2013下午4:30
我在c#编程,并使用OLE DB从访问数据库拉数据。'To'和'From' DateTime值是从GUI上的DateTimePicker控件检索的。我试图查询数据在'receiveDateTime'字段我的数据源-它是存储在DateTime格式的访问。
我的代码如下:
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN "
+ fromDateTime.Value.ToString("g") + "AND " + toDateTime.Value.ToString("g")";
loadDataGrid(SQLQuery);
任何解决方案或建议都将不胜感激。
谢谢,Allan。
1-似乎您忘记了日期值之间的单引号:
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN '"
+ fromDateTime.Value.ToString("g") + "' AND '" + toDateTime.Value.ToString("g") +"' ";
2-如果你也使用参数化的参数会更好:
SqlConnection con = new SqlConnection(MyconnectionString);
con.Open();
string SQLQuery = "SELECT EmailID, ServerName, receiveDateTime, Type, status, received, processed"
+ "FROM EmailTable, EmailTypesTable, ServerTable, StatusTable"
+ "WHERE EmailTypesTable.emailTypeID = EmailTypesTable.EmailType "
+ "AND ServerTable.ServerID = EmailTable.serverID "
+ "AND StatusTable.statusID = EmailTable.statusID "
+ "AND EmailTable.receiveDateTime BETWEEN @dateFrom AND @dateTo";
SqlCommand cmd = new SqlCommand(SQLQuery );
cmd.Parameters.AddWithValue("@dateFrom", fromDateTime.Value.ToString("g"));
cmd.Parameters.AddWithValue("@dateTo", toDateTime.Value.ToString("g"));
SqlDataReader reader = cmd.ExecuteReader();
//...
您可以通过尝试直接在数据库
中执行此查询来猜出问题。(我已经使用SQLConnection, SQLCommand…在这里,您需要根据您正在使用的连接更改该部分。
对于将来在比较DateTime值时遇到此问题的任何人,将c# DateTime作为OLE自动化日期传递给数据库工作!
为了访问这个值,你可以使用ToOADate()方法。
例如:SqlConnection con = new SqlConnection(MyconnectionString);
con.Open();
string SQLQuery = "SELECT EmailID, receiveDateTime "
+ "WHERE EmailTable.receiveDateTime "
+ "BETWEEN @dateFrom AND @dateTo";
SqlCommand cmd = new SqlCommand(SQLQuery );
cmd.Parameters.AddWithValue("@dateFrom", fromDateTime.Value.ToOADate());
cmd.Parameters.AddWithValue("@dateTo", toDateTime.Value.ToOADate());
这很奇怪,因为尽管DateTime值在DataGrid中以通用的DateTime格式出现,但数据库必须这样读取它们:
一般日期时间格式:26/04/2013 9:47 AM
OLE Automation Date: 41390.4082198032
谢谢你给我指了正确的方向。