select data from ms access database by date in c#

2019-06-14 13:05发布

问题:

i want to select data from ms access database in c# i use this query

da = new OleDbDataAdapter(
    "SELECT [Column1],[Column2],[Column3],[Date] from [Total] Where [Date] between #" 
        + dateTimePicker2.Value.ToString() 
        + "# AND #" 
        + dateTimePicker3.Value.ToString() 
        + "#", 
    VCON);

it's return me null please help me.

回答1:

You must format date like :

dateTimePicker2.Value.ToString("yyyy/MM/dd")

you can also do :

da = new OleDbDataAdapter(
        "SELECT [Column1],[Column2],[Column3],[Date] from [Total] Where [Date] between "
            + dateTimePicker2.Value.ToString("#yyyy/MM/dd#")
            + " AND "
            + dateTimePicker3.Value.ToString("#yyyy/MM/dd#") ,
        VCON);

But, I advice you to use the Parameter to avoid SQL injections , like this :

string query = "SELECT [Column1],[Column2],[Column3],[Date] from [Total] Where [Date] " +
               "BETWEEN @startDate AND @endDate";
OleDbCommand cmd = new OleDbCommand(query, VCON);
cmd.Parameters.AddWithValue("@startDate ", DbType.DateTime).Value = 
                                            dateTimePicker1.Value.ToString("yyyy/MM/dd");
cmd.Parameters.AddWithValue("@endDate ", DbType.DateTime).Value = 
                                            dateTimePicker2.Value.ToString("yyyy/MM/dd");
da = new OleDbDataAdapter(cmd);