在c#中使用msAcc在两个日期之间搜索数据

时间:2013-12-30 12:54:23

标签: c# c#-4.0 c#-2.0

以下查询给我一个错误我如何纠正它....

select * from invoice_master where  modify_date between '11/3/2013 5:54:55 PM' 
and '12/30/2013 5:54:55 PM';

String qu = "select * from invoice_master where  modify_date between '" + 
            dateTimePicker1.Value + "' and '" + dateTimePicker2.Value + "' ;";

DataTable d = new DataTable();

d = ds.get_date_Table(qu);

dataGridView1.DataSource = d;
dataGridView1.Show();

public DataTable get_date_Table(String query)
{
    OleDbConnection con = new OleDbConnection(connection);
    OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);


    DataTable dt = new DataTable();

    try
    {
        adapter.Fill(dt);
    }
    catch (Exception ex)
    {
        throw ex;
    }

    return dt;
}

1 个答案:

答案 0 :(得分:1)

一如既往,这种问题是由于字符串连接习惯造成的 您应始终使用参数化查询,并将负担正确引用到数据库引擎代码

String qu = "select * from invoice_master where  modify_date between ? and ?" + 
using(OleDbConnection con = new OleDbConnection(connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(query, con))
{
    DataTable dt = new DataTable();
    adapter.SelectCommand.Parameters.AddWithValue("@p1", dateTimePicker1.Value)
    adapter.SelectCommand.Parameters.AddWithValue("@p2", dateTimePicker2.Value)
    adapter.Fill(dt);
}

通过这种方式,需要包含日期值的任何字符(顺便使用MSAccess它是#符号,但其他数据库可能有不同的要求)它由框架添加代码比你和我更了解如何将datetime值传递给数据库引擎。