I have a problem trying to parameterize some “dynamic” SQL build in an existing C# class used by an ASP app. The environment is:
- Win Server 2008
- .NET 3.0
- C#
- DB2 9.x ([IBM][CLI Driver][DB2])
The existing code just concatenates the SQL with the param strings in a long SQL string – which is of course at risk for SQL injection. As is my practice whenever I see this, I tend to change the code to use parameters. But with this code I am failing. I have tried “@” and I have tried “?” – the latter is what I understand to be necessary for ODBC.
Here is a simplified code snippet (forgive me if I don’t format it right – this is my first question) that I have compiled and run:
private DataSet test(String schemaName )
{
String sortField = "TABLE_NAME.COLUMN_NAME";
String sortDirection = "ASC";
OdbcConnection conn = new OdbcConnection();
DataSet ds = new DataSet();
string connStr = ConfigurationManager.AppSettings[schemaName] + dbUser;
try
{
conn.ConnectionString = connStr;
OdbcCommand cmd = new OdbcCommand("SELECT * FROM TABLE_NAME ORDER BY ? ? ");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(sortField);
cmd.Parameters.Add(sortDirection);
logger.log("cmd SQL = \t" + cmd.CommandText );
OdbcDataAdapter da = new OdbcDataAdapter(cmd);
da.Fill(ds);
return ds;
}
catch (Exception ex)
{
ex.Data.Add("Location:", "test()");
ex.Data.Add("Connection", conn.ConnectionString);
logger.logException(ex);
throw ex;
}
finally
{
conn.Close();
}
}
Log printout:
cmd SQL = SELECT * FROM TABLE_NAME ORDER BY ? ?
Where TABLE_NAME is of course the table I am querying.
What I get in return is this (some proprietary info removed:
EXCEPTION occured at 4/26/2012 12:29:41 PM ERROR [42601] [IBM][CLI
Driver][DB2] SQL0104N An unexpected token “?” was found following “”.
Expected tokens may include: “MICROSECONDS MICROSECOND SECONDS SECOND
MINUTES MINUTE HOURS”. SQLSTATE=42601
at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)Connection Driver={IBM DB2 ODBC DRIVER};
…..
Changing this to a stored proc is not allowed.
Upgrading to a later version of .NET is not allowed.
Changing/upgrading the ODBC driver is not allowed.
What I am seeing indicates to me that the “?” parameter is not being replaced.
I have tried AddWithValue() and I have tried Add(OdbcType.VarChar).Value = sortField (or something to that effect).
I am kind of at my whit’s end – all of the googling and searching here indicates to me that the code above should work, but so far I have not been able to get the parameters in the SQL substituted with the variables.
Thanks in advance.
The reason the
?is an unexpected token is because you are using it in theORDER BYclause (which I don’t think is allowed).The reason to use parameters is to mitigate the risks of user input. When building your query, if the
ORDER BYfield and direction are not coming via user input, you are safe in building the query with concatenation.Only use the
?in theWHEREclause: