Parameterized ODBC Query works with VarChar but not DateTime?

三世轮回 提交于 2019-12-13 08:45:21

问题


As followup to this question, everything was working when I was manually defining the dates like 2016-05-01 as strings/varchars. However, when I went to convert to datetime I'm now getting empty results again. This is the code as it stands:

log("Connecting to SQL Server...");
string connectionString = "DSN=HSBUSTEST32;";

// Provide the query string with a parameter placeholder.
string queryString = "SELECT COUNT(*) FROM Table WHERE myDateTime >= ? AND myDateTime < ?";

// Specify the parameter value.
DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddHours(-1);

using (OdbcConnection connection = new OdbcConnection(connectionString))
{
    // Create the Command and Parameter objects.
    OdbcCommand command = new OdbcCommand(queryString, connection);
    command.Parameters.Add("@startDate", OdbcType.DateTime).Value = startDate;
    command.Parameters.Add("@endDate", OdbcType.DateTime).Value = endDate;

    try
    {
        connection.Open();
        OdbcDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            log(reader[0].ToString());
        }
        reader.Close();
    }
    catch (Exception ex)
    {
        log(ex.Message);
    }
}

Again, if I were to replace the following:

DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddHours(-1);

with

string startDate = "2016-08-23";
string endDate = "2016-08-24";

And then change the OdbcType to VarChar everything works fine.


回答1:


I believe your error is with the date range.

// Specify the parameter value.
DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddHours(-1);

endDate will be 1 hour less than start date. The comparison operator in your query is greater than first parameter and less than second parameter.

For example:

string queryString = "SELECT COUNT(*) FROM Table WHERE myDateTime >= '8/26/2016 14:30:00' AND myDateTime < '8/26/2016 13:30:00'";

No date exists that's greater than 2:30pm and less than 1:30pm of the same date. :)

Maybe you meant

DateTime startDate = DateTime.Now;
DateTime endDate = startDate.AddHours(1);



回答2:


The problem has to do with your dateformat. What you are passing at the moment is a date with a time, but you wanna have only the date. You should be good to go if you use the Datepart only from the Datetime.

You could do this either with a string format like this:

DateTime.Now.ToString("yyyy-MM-dd") 

Or by using the date property:

DateTime.Now.Date;


来源:https://stackoverflow.com/questions/39174830/parameterized-odbc-query-works-with-varchar-but-not-datetime

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