select data from ms access database by date in c#

拜拜、爱过 提交于 2019-12-10 12:16:03

问题


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


来源:https://stackoverflow.com/questions/37883432/select-data-from-ms-access-database-by-date-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!