Misha Narinsky
Misha Narinsky

Reputation: 687

How to parameterize complex OleDB queries?

I'm trying to refactor some code that is using strings concatenation for creating SQL commands (which makes it vulnerable for a SQL injection). Basically all I'm trying to do is to replace all the string sqlToExecute = String.Format(..) statements with a SQL command and a List of OleDB parameters.

I understand how this can be done for simple cases like String.Format("Select * from myTable where id = {0}", id). However, I could not find a set of good examples for more complex SQL queries.

Here are some of the queries that I'm not sure how exactly I can parameterize:

1. Parameters are used for both column name and alias; Parameter consists of two variables:

    selQueryBldr.AppendFormat("SELECT * FROM {0} {1} 
    INNER JOIN ColChange CC ON CC.TableRecordID = {1}.{2} and CC.EntityID='{3}'",
    entity.StageTableName, stageTableAlias, entity.PrimaryKey, entity.EntityID);

2. Same parameter is used in multiple SQL IN clauses

SQL Query:

      SELECT A.TablePrefix ...
      FROM Entity E
      INNER JOIN App A
      ON A.AppID = E.AppID
      WHERE E.AppID in (#APPIDS#)

      UNION

      SELECT A.TablePrefix ...
      FROM EntityB EB
      INNER JOIN App A
      ON A.AppID = EB.AppID
      WHERE EB.AppID in (#APPIDS#)

Currently the parameter is added in the code by using String.Replace() method:

    sqlQuery = sqlQuery.Replace("#APPIDS#",idList);

3. Using variables as a parameter name and a parameter value:

    StringBuilder dataQuery = new StringBuilder("Select * from {0} WHERE {1}='{2}'",
    tableName, primaryKey[0], changeRow["TableRecordID"]);

4. Variable used a part of the unicode parameter:

    sSQL = string.Format("SELECT name FROM sysobjects WHERE id = object_id(N'[dbo].[{0}]')",
    sSPName);


Also, all of these examples are using OleDb classes (OleDbConnection/OleDbCommand etc.), thus as far as I understand named parameters can not be used here.

Upvotes: 1

Views: 1889

Answers (1)

DRapp
DRapp

Reputation: 48139

Different back-ends allow (or not) either named parameters, or "?" place-holders for parameters, so what you would do is build your query something like

OleDbCommand oCmd = new OleDbCommand( YourConnection, "select * from someTable where yourColumn = ? and otherColumn = ?" );

oCmd.Parameters.AddWithValue( "parm1", YourVariable.FormattedHoweverNeeded );
oCmd.Parameters.AddWithValue( "parm2", anotherVariable.FormattedHoweverNeeded );

If the columns are expecting strings, ensure a string. If expecting numeric (int, double, float, etc), leave as that type too, or other (date/time, etc)

Just note... if not doing named parameters (as I have with "?" place-holder), the parameters must be added in the same sequence as the "?" are placed in the SQL command.

Upvotes: 1

Related Questions