String to SQLCHAR* or LPCSTR Conversion

I've got another question regarding my program. Considering that I can't seem to get str.c_str() to work, how would I go about getting the resulting code to work?
I want to convert a string into a LPCSTR or a SQLCHAR* so I can have a variable component to the SQL statement. I tried turning that whole string that I'm currently incorrectly casting as a SQLCHAR* into an initialized string and then using .c_str() to get the const char * of it, but this only made the compiler happy, not the program. When this happens, the statement handle becomes invalid because whatever I assign the str.c_str value becomes undefined (according to VS2012 compiler).

1
2
SQLExecDirect(sqlstatementhandle, (SQLCHAR*)("select PID from Rgs_MDR where PID = \'" + sPID
            + "\';"), SQL_NTS);


sPID is a string of eight numbers in case you needed that information. Ignore the seemingly uselessness of the SQL statement. Thanks in advance for any replies.
Considering that I can't seem to get str.c_str() to work, how would I go about getting the resulting code to work?
I want to convert a string into a LPCSTR


That is exactly what c_str() does:

1
2
std::string foo = "some string data";
LPCSTR bar = foo.c_str(); // that's all there is to it 


The only thing about this is that LPCSTR is a POINTER and is not actually a string. Therefore if 'foo' goes out of scope, the string data is lost and the pointer goes bad:

1
2
3
4
5
6
LPCSTR ptr;
{
    std::string foo = "data that dies";
    ptr = foo.c_str();
}  // <- foo goes out of scope and dies here
// <-  therefore, 'ptr' is now a BAD POINTER and points to garbage 


Remember that LPCSTR is just a typedef: typedef const char* LPCSTR;

I don't know what SQLCHAR is, but it's probably the same.


With that in mind.... this code:
1
2
SQLExecDirect(sqlstatementhandle, (SQLCHAR*)("select PID from Rgs_MDR where PID = \'" + sPID
            + "\';"), SQL_NTS);


Making the following assumptions:
- SQLCHAR is just a typedef of char
- 'sPID' is a std::string
- The 2nd param of SQLExecDirect actually takes a const pointer to string data


you should be able to just do this:

1
2
3
SQLExecDirect(sqlstatementhandle,
   ("select PID from Rgs_MDR where PID = \'" + sPID + "\';").c_str()
   , SQL_NTS);
Yeah, okay, thanks for the response. You're completely correct that SQLCHAR is a typedef and that it's basically the same thing. Your syntax works flawlessly just like the more cumbersome version which I tried, but the result is the same. I now however know that it's a problem elsewhere not with what I thought it was in the original post. An interesting note, the program backtracks to the statement before it, and I've never seen that before, but that's another question for another day.

You really helped me connect the dots here.
Topic archived. No new replies allowed.