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

怎甘沉沦 提交于 2019-12-11 04:09:59

问题


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


来源:https://stackoverflow.com/questions/39174553/cant-get-parameters-to-work-with-odbcconnection-in-c-sharp

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