Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

c# - Parameterized ODBC Query works with VarChar but not DateTime?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...