0

I have the next code:

public static List<T> ExecuteQuery<T>(string qry, Dictionary<string, object> parameters = null)
    {
        using (var connection = new OdbcConnection(ConnectionString))
        {
            connection.Open();
            var command = new OdbcCommand(qry, connection);
            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    command.Parameters.AddWithValue(parameter.Key, parameter.Value);
                }
            }
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    // ...
                }
            }
        }
    }

When I execute something like:

ExecuteQuery<MyClass>("SELECT * FROM MYTABLE WHERE ID = 1");

It returns all the correct data. But when I send this:

ExecuteQuery<MyClass>(
    "SELECT * FROM MYTABLE WHERE ID = @Id", 
    new Dictionary<string, object> { { "@Id", 1 } });

doesn't return anything. I've tried with command.Parameters.Add but is the same history.

So, where is my error?

Thanks to everyone.

1 Answer 1

1

Try substituting the named parameter with a ?, which I believe is what OdbcCommand uses.

ExecuteQuery<MyClass>("SELECT * FROM MYTABLE WHERE ID = ?",
                      new Dictionary<string, object> { { "@Id", 1 } });

Also, since a Dictionary doesn't guarantee order, you may want to replace that with a List<T> in the event you have more than one parameter. A list guarantees order.

I'd also suggest specifying the OdbcType and not just adding all your parameter values as objects. It has to infer the correct data type otherwise, and it may guess wrong. You could create a more permanent class... here I decided to just use a Tuple<T,T,T>.

public static List<T> ExecuteQuery<T>(string qry, List<Tuple<string, OdbcType, object>> parameters = null)

...
...

foreach (var parameter in parameters)
{
    command.Parameters.Add(parameter.Item1, parameter.Item2).Value = parameter.Item3;
}
1
  • 1
    I like your advice about the OdbcType, but my database provider could change in any second so it means that I need to use the most separate way possible
    – DannSaHa
    May 6, 2015 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.