Search code examples
c#sqlodbcintersystems-cache

Can't get parameters to work with OdbcConnection in C#


I'm running a query with a couple date constraints. If I execute the code below with the dates hardcoded and no parameters, I get a result I expect (a simple integer). However, when I try to use parameters I get an empty result set. No errors, just no results.

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

string queryString = "SELECT COUNT(*) FROM Table WHERE myDateTime >= '?' AND myDateTime < '?'";
//string queryString = "SELECT COUNT(*) FROM Table WHERE myDateTime >= '@startDate' AND myDateTime < '@endDate'";

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

using (OdbcConnection connection = new OdbcConnection(connectionString))
{
    OdbcCommand command = new OdbcCommand(queryString, connection);
    command.Parameters.AddWithValue("startDate",startDate);
    command.Parameters.AddWithValue("endDate", endDate);
    //command.Parameters.Add("startDate", OdbcType.VarChar).Value = "2016-08-23";
    //command.Parameters.Add("endDate", OdbcType.VarChar).Value = "2016-08-24";

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

As you can see I've tried both named parameters as well as using the ? placeholder. I've also tried a couple different methods of adding the parameters, Add() and AddWithValue(), though truthfully I don't understand the difference.

What is causing the empty results?


Solution

  • The problem with your query like i said before is the single quote. If you pass in the value without a parameter you need to use those single quotes because this defines a string in a statement.

    With the parameters the framework handels all this stuff for you. It also checks for sql injection and removes dissalowed chars. Especially for string and datetime values this is really helpful.