I have a huge program which has already tons of queries with parameters.
In the whole project I accessed to the database only through IDbConnection, IDbCommand, etc interfaces instead of using directly OleDbConnection, OleDbCommand, etc.
This allowed me to use different database engines and connection types with my application. Until now, for example, I used OleDbConnection to connect to MS SQL Server databases, OdbcConnection for MySql and SQLiteConnection from an external library for, obviously, SQLite.
Now I would like to try replacing the OleDbConnection with SqlConnection to connect to SQL Server but I found some problems with the parametrized queries.
I was used to do something like that with parametrized queries:
IDbCommand cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE foo SET field1=? WHERE ID=?";
DbUtils.AddParameter(cmd, DbType.StringFixedLength, "hello");
DbUtils.AddParameter(cmd, DbType.Int32, 1);
cmd.ExecuteNonQuery();
The AddParameter static method checks the type of the IDbCommand and adds the parameter value to it.
This works with the three connection types I specified above, but doesn't work with SqlConnection, it throws the error: Incorrect syntax near '?'.
SqlCommand seems to require named parameters to work:
IDbCommand cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE foo SET field1=@pfield1 WHERE ID=@pID";
DbUtils.AddParameter(cmd, DbType.StringFixedLength, "@pfield1", "hello");
DbUtils.AddParameter(cmd, DbType.Int32, "@pID", 1);
cmd.ExecuteNonQuery();
Do you know if it is possibile to avoid using named parameters to maintain compatibility with the other connection types?
Thanks!
Francesco
@instead of??@in your command , it is too normal to say that error because it is not a named parameter with just itself.