#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2003
    Location
    USA
    Posts
    144
    Rep Power
    12

    passing C++ variables to SQL statement


    Hello,

    I have a recordset open function and would like to limit the returned recordset with a WHERE statement. It works without problems if the value after WHERE is just a literal string, however, that value must be a variable that will change. When I substitue with a variable, the program crashes.

    How can I insert a variable there instead of using a predefined value??

    Doesnt work:

    CString MyVariable = "helpme";

    recordset.Open(AFX_DAO_USE_DEFAULT_TYPE, "SELECT * FROM MyTable WHERE NameField = MyVariable",NULL);


    Does work:

    recordset.Open(AFX_DAO_USE_DEFAULT_TYPE, "SELECT * FROM MyTable WHERE NameField = 'helpme'",NULL);


    I am using visual C++ and trying to connect to a Microsoft Access database if that makes a difference,

    Thank you!!!
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    We were just talking about this:

    Code:
    CString MyVariable = "helpme";
    
    recordset.Open(AFX_DAO_USE_DEFAULT_TYPE, "SELECT * FROM MyTable WHERE NameField = '"+MyVariable+"'",NULL);
    Now, that is assuming that recordset.Open() accepts a CString as its second parameter. If it does not, then you should create a CString (eg, MySQLstring) for the entire SQL statement, concatenate your variable value in as shown, and do whatever you need to to get Open to read it, like maybe MySQLstring.GetBuffer().
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2003
    Location
    USA
    Posts
    144
    Rep Power
    12

    passing C++ variable to SQL success


    Thank you for your reply -

    I also happened upon a way to do it as follows:

    CString MyVariable = "Mr. Bigglesworth";

    CString sSql;
    sSql.Format("SELECT * FROM NamesTable WHERE NameField = '%s' ", (LPCSTR)MyVariable);

    recordset.Open(AFX_DAO_USE_DEFAULT_TYPE, sSql, NULL);

    Diabolical!

    Hope that helps someone down the road.
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    Yep, does the same thing. Perl isn't the only language with more than one way.

    Basically, CString's Format() method implements the functionality of the sprintf function. I haven't played with MFC for a while, so it slipped my mind.

    Nice to see that Open takes a CString argument.

IMN logo majestic logo threadwatch logo seochat tools logo