在数据库c#中的两个日期之间搜索

时间:2015-10-13 04:18:30

标签: c#

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";
}

我想在两个日期和员工姓名之间搜索记录。有人可以帮我查询一下吗?     public void 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();

    }

此代码正常工作,此处使用的datetimepicker与我将在LoadAttendance中使用的相同。

3 个答案:

答案 0 :(得分:2)

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'。

如果它不起作用。尝试

DateField> = @fromdt AND DateField< @todt

答案 1 :(得分:0)

试试这个

SELECT * FROM AttendanceDatabase 
WHERE EmpName = '" + txtEmpName.Text + "' 
AND 
(DateField BETWEEN '" + DateTime.Parse(StartDate) + "' 
    AND '" + DateTime.Parse(EndDate) + "')"

答案 2 :(得分:0)

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();
    }

这里我是如何解决大声笑的。