Click here to Skip to main content
15,905,136 members
Articles / Programming Languages / C#
Tip/Trick

Parameters - SqlCommand vs. OledbCommand and OdbcCommand

Rate me:
Please Sign up or sign in to vote.
4.90/5 (9 votes)
25 Jul 2011CPOL1 min read 78.6K   5   10
A quick tip on using OledbCommand and OdbcCommand
Using OledbCommand and OdbcCommand can be quite confusing, if you have used SqlCommand for some time. One difference is on the configuration of their parameters. For SqlCommand, it doesn't really care about the order of the parameters on your object so long as those parameters exist in the query. A snippet like the following would work. Notice how the parameters are positioned on the CommandText property and the order on how it is added on the object.
C#
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConnString"]);
SqlCommand comm = new SqlCommand();
SqlDataAdapter dAdpter = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
comm.Connection = conn;
comm.CommandText = "SELECT FirstName, LastName FROM tblMyChicks WHERE Age > @ageParam AND  LastName = @lNameParam";
comm.Parameters.AddWithValue("@lNameParam", "NoLastName");
comm.Parameters.AddWithValue("@ageParam", 18);
dAdpter.Fill(dt);

On the other hand, OleDbCommand and OdbcCommand does not support named parameters, and use ? placeholders instead. An example would be the following:
comm.CommandText = "SELECT FirstName, LastName FROM tblMyChicks WHERE Age > ? AND  LastName = ?";

One might believe that named parameters will work as writing a statement like SELECT FirstName, LastName FROM tblMyChicks WHERE Age > @ageParam AND LastName = @lNameParam is valid and won't throw any error(yes this is valid, and I believe its better to write them this way, for readability purposes). But in reality, it just treats it as a placeholder. As opposed to SqlCommand, it is important to take note of the order of how the parameters are added on the command object. The following code will result to a Data type mismatch in criteria expression. error.
C#
OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["DBConnString"]);
OleDbCommand comm = new OleDbCommand();
OleDbDataAdapter dAdpter = new OleDbDataAdapter(comm);
DataTable dt = new DataTable();
comm.Connection = conn;
comm.CommandText = "SELECT FirstName, LastName FROM tblMyChicks WHERE Age > @ageParam AND  LastName = @lNameParam";
comm.Parameters.AddWithValue("@lNameParam", "NoLastName");
comm.Parameters.AddWithValue("@ageParam", 18);
dAdpter.Fill(dt);

Conclusion


Here are a few pointers that I hope I have explained:

1. SqlCommand uses named parameters, and the order of added parameter objects does not matter, so long as the parameter names exist on the query.
2. OleDbCommand and OdbCommand does not support named parameters and uses the ? placeholder instead, so the order of the parameters is important. However, you can give names to its parameters instead of using ?, for readability purposes.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Philippines Philippines
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionDisagree Pin
Maciej Los6-Dec-14 4:38
mveMaciej Los6-Dec-14 4:38 
GeneralMy vote of 5 Pin
ajit3025-Nov-14 23:18
professionalajit3025-Nov-14 23:18 
GeneralMy vote of 5 Pin
Herbisaurus21-Aug-13 21:56
Herbisaurus21-Aug-13 21:56 
NewsSome results from my research Pin
randomusic22-Nov-12 11:53
randomusic22-Nov-12 11:53 
I have been doing some tests with using OleDbCommand and its parameters collection against an Access DB. The ordering of parameters is of course necessary. But there is a problem that you can encounter when using question marks as place holders.

Say you have a query ("stored procedure") that looks like this, very simplified here:

SQL
parameters
  prmFirstNumber Long,
  prmSecondNumber Long;
select
  fullName
from
  tblPersons
where 
  numberOfCars < prmFirstNumber And
  numberOfPets < prmSecondNumber And
  numberOfBooks beteween prmFirstNumber And prmSecondNumber

Here you see that simply changing to question marks would break the query.

I have found though, as a solution to this, that you can actually use names for parameters (as you point out in the article). So you can let the query above remain as it is. You just have to use the same order when you run the query. Like in this case, you first add the parameter prmFirstNumber and then prmSecondNumber, and then you run the query.

When reusing parameters, i.e. executing a query more than once and setting new values for the parameters each time, one must call the prepare method of the command object right after having defined the parameters. There are some details there that need to be fulfilled too, look at the documentation for "prepare". Not calling prepare causes strange behaviour without error messages which can corrupt your database or cause wrong information to be presented to users.

I can add also that when queries are stored in the Access DB with parameters specified, like in my example above, then the ordering of the parameters is unambiguously defined by the parameters-section.

I also made a routine, "retrieveDeclaredJetParametersInOrder", which automatically populates an OleDbCommand object with those named parameters, in the correct order. So my code can look like this:

VB
Dim cmd As New OleDbCommand("qryInAccessDB", Conn)
cmd.CommandType = CommandType.StoredProcedure
Conn.Open()
retrieveDeclaredJetParametersInOrder(cmd)
cmd.Parameters("prmOneOfTheParametersPerhapsTheLastOneDeclared").Value = 1
cmd.Parameters("prmAnotherone").Value = 20
cmd.Parameters("prmYetAnotherPerhapsTheFirstOneDeclared").Value = 300
cmd.ExecuteNonQuery()
Conn.Close()
So, as you see, I can handle it as if parameters are named, and never have to bother with their ordering.

The retrieveDeclaredJetParametersInOrder of course adds extra time to execution, since it involves an extra call to the DB, where it retrieves the SQL-text and then parses out the parameter names and types.

Magnus

modified 24-Nov-12 16:29pm.

GeneralRe: Some results from my research Pin
walterhevedeich21-Aug-13 22:56
professionalwalterhevedeich21-Aug-13 22:56 
GeneralRe: Some results from my research Pin
randomusic23-Aug-13 0:43
randomusic23-Aug-13 0:43 
GeneralReason for my vote of 5 Its an important tip. Few months ago... Pin
thatraja8-Oct-11 20:08
professionalthatraja8-Oct-11 20:08 
GeneralRe: Thanks Raja. Error messages can really be confusing sometime... Pin
walterhevedeich10-Oct-11 3:16
professionalwalterhevedeich10-Oct-11 3:16 
GeneralReason for my vote of 3 good work Pin
Mohammed Abdulgadir1-Aug-11 20:09
Mohammed Abdulgadir1-Aug-11 20:09 
GeneralReason for my vote of 4 Quick and to the point. Good contrib... Pin
BrianBissell1-Aug-11 16:34
BrianBissell1-Aug-11 16:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.