I have to query a DB2 database using an existing ODBC connection. Executing simple queries works as expected, but as soon as I try to execute a parameterised query it doesn't work:
SELECT
ColumnA,
ColumnB
FROM
MyTable
WHERE
ColumnA = ? AND
ColumnB = ?
Using the ?
was suggested in other posts, but I always get empty results (no error messages though). When I try the standard SQL way with named parameters (and changing the SQL statement to ColumnA = @ColumnA AND ColumnB = @ColumnB
as shown below
odbcCommand.Parameters.AddWithValue( ColumnA", 1234 );
odbcCommand.Parameters.AddWithValue( ColumnB", 9999);
the following error message is shown:
System.Data.Odbc.OdbcException: ERROR [42S22] [IBM][CLI Driver][DB2] SQL0206N "@ColumnA" is not valid in the context where it is used. SQLSTATE=42703...
Using odbcCommand.Parameters.Add( new OdbcParameter( "ColumnA", Integer ){ Value = 1234 } );
instead shows that this is deprecated (and also doesn't work). I'd like to avoid using concatenated SQL statements, but I can't find a way to get parameterised queries working against a DB2 database.
You failed to mention your DB2 version. In DB2 9.7 and later there is a driver parameter DB2NETNamedParam
that controls this behaviour. Check your db2cli.ini
file.
I suspect that named parameters may not be supported in earlier versions.