在数据库 c# 中的两个日期之间搜索
本文关键字:两个 日期 之间 搜索 数据库 | 更新日期: 2023-09-27 18:17:27
public void LoadAttendance()
{
DataAdapter = new OleDbDataAdapter("SELECT * FROM AttendanceDatabase where EmpName = '" + txtEmpName.Text + "'", con);
DataTable = new DataTable();
DataAdapter.Fill(DataTable);
dgvAttendance.DataSource = DataTable;
dgvAttendance.Columns[1].DefaultCellStyle.Format = "h:mm tt";
dgvAttendance.Columns[2].DefaultCellStyle.Format = "h:mm tt";
}
我想搜索两个日期和员工姓名之间的记录。有人可以帮助我查询吗? 公共无效 FillPresentDays(( {
Public void FillPresentDays
{
con.Open();
cmd = new OleDbCommand("Select COUNT(*) from AttendanceDatabase WHERE EmpName =@EmpName and Date between @d1 and @d2", con);
cmd.Parameters.AddWithValue("@EmpName", txtEmpName.Text);
cmd.Parameters.AddWithValue("@d1", dtDate1.Value.Date);
cmd.Parameters.AddWithValue("@d2", dtDate2.Value.Date);
cmd.ExecuteNonQuery();
int count = (int)cmd.ExecuteScalar();
txtPdays.Text = count.ToString();
con.Close();
LoadAttendance();
}
此代码正在工作,此处使用的日期时间选择器与我将在 LoadAttendance 中使用的相同。
public void LoadAttendance()
{
DateTime fromdt = DateTime.ParseExact("1/1/2009", "M/d/yyyy", new CultureInfo("en-US"));
DateTime todt = DateTime.ParseExact("1/1/2010", "M/d/yyyy", new CultureInfo("en-US"));
DataAdapter = new OleDbDataAdapter("SELECT * FROM AttendanceDatabase where EmpName = '" + txtEmpName.Text + "' AND (DateField BETWEEN '" + fromdt +"' AND '" + todt + "') ", con);
DataTable = new DataTable();
DataAdapter.Fill(DataTable);
dgvAttendance.DataSource = DataTable;
dgvAttendance.Columns[1].DefaultCellStyle.Format = "h:mm tt";
dgvAttendance.Columns[2].DefaultCellStyle.Format = "h:mm tt";
}
使用日期时间格式,而不是"m/d/yyyy"。
如果它不起作用。
日期字段>= @fromdt 和日期字段 <@todt
试试这个
SELECT * FROM AttendanceDatabase
WHERE EmpName = '" + txtEmpName.Text + "'
AND
(DateField BETWEEN '" + DateTime.Parse(StartDate) + "'
AND '" + DateTime.Parse(EndDate) + "')"
public void LoadAttendance()
{
con.Open();
cmd = new OleDbCommand("Select * from AttendanceDatabase WHERE EmpName = @EmpName and Date between @d1 and @d2", con);
cmd.Parameters.AddWithValue("@EmpName", txtEmpName.Text);
cmd.Parameters.AddWithValue("@d1", dtDate1.Value.Date);
cmd.Parameters.AddWithValue("@d2", dtDate2.Value.Date);
DataAdapter = new OleDbDataAdapter(cmd);
DataTable = new DataTable();
DataAdapter.Fill(DataTable);
dgvAttendance.DataSource = DataTable;
con.Close();
}
这是我如何解决哈哈的。