Can't get parameters to work with OdbcConnecti

2019-07-22 07:56发布

问题:

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?

回答1:

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.



回答2:

Keep using this:

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

but try this:

command.Parameters.AddWithValue("@startDate",startDate);
command.Parameters.AddWithValue("@endDate", endDate);