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.
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.
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.