Link to home
Start Free TrialLog in
Avatar of agomes
agomes

asked on

CDaoRecordset with SetParamValue()

I would like to use a parameterized query with CDaoRecordset, using the members m_nParam and SetParamValue(). I have a query like

select * from TabX where FieldX = [ValueX] And FieldY = [ValueY]

where [ValueX] and [ValueY] are the parameters I would like to change at run time.

I am currently instantiating a CDaoRecorset child and using this query (with the actual values instead of parameter names) by calling CDaoRecordset::Open().

How do I write a parameterized query? How do I use SetParamValue() to set the actual values of the parameters?

Many thanks for your help.
Avatar of Roshan Davis
Roshan Davis
Flag of United States of America image

Try this

    CDaoDatabase db;
    CDaoQueryDef query( &db );

    try
    {
        db.Open( "C:\\DB1.mdb" );
        query.Open(NULL, "select * from TabX where FieldX = [ValueX] And FieldY = [ValueY]");
        query.SetParamValue( "FieldX", COleVariant( (long)nFieldX, VT_I4 ) );
      query.SetParamValue( "FieldY", COleVariant( (long)nFieldY, VT_I4 ) );

       query.Execute();
    }
    catch( CDaoException* e )
    {
        AfxMessageBox( e->m_pErrorInfo->m_strDescription,
            MB_ICONEXCLAMATION );
        e->Delete();
    }
    query.Close();
    db.Close();

Good Luck
Avatar of agomes
agomes

ASKER

Thanks roshmon, I will try it, but I need to use a CDaoRecordset. Can I just CDaoRecordset::Open( query ) and not query.Execute()?

Anyway, we are using CDaoQueryDef, and not the methods in CDaoRecordset. What these methods are for (m_nParam, SetParamValue(), GetParamValue())?

Thanks again.

ASKER CERTIFIED SOLUTION
Avatar of Roshan Davis
Roshan Davis
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of DanRollins
DanRollins
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes thats the simplest. But parameter is needed when the query is executing several times with different condition values.
In that case Query parsing will occur once.
Avatar of agomes

ASKER

Many thanks roshmon, DanRollins, and sorry for the delay.

I wanted to use parameters to optimize the use of my CDaoRecordset, once I needed to change only the parameters from time to time, but I could not make it work, neither using MFC example, nor using roshmon's (maybe because of DAO version?), so I did opt to close and open the CDaoRecordset again (ugly, but it works).

It seems roshmon's answer is on the right direction, maybe it needs some adjustment or I am using a wrong DAO version.

Many thanks for your time.