0

Im working on a program that are accessing a SQL server.

I've established the connection, and i can get the stand i want, but only when my SQL Query is static.

I've read a post in here, where the same question was asked, tried his solution, which sadly didn't work (8 years old post also).

The function used to gain the Query is the following:

SQLWCHAR ConstructQuery()
{
    wstring temp = L"SELECT Something FROM somewhere WHERE condition"; 
    SQLWCHAR statement = (SQLWCHAR)temp.c_str();
    return statement;
}

and my code for running this query is as follows:

SQLStatement = ConstructQuery();
SQLExecDirect(sqlStmtHandle,&SQLStatement, SQL_NTS))
        

SQLCHAR sqldata[SQL_RESULT_LEN];
        SQLINTEGER ptrsqldata;
        while (SQLFetch(sqlStmtHandle) == SQL_SUCCESS) {
            SQLGetData(sqlStmtHandle, 1, SQL_CHAR, sqldata, SQL_RESULT_LEN, &ptrsqldata);
            //display query result
            cout << "\nQuery Result:\n\n";
            cout << sqldata << endl;
        
        }

The code runs, but i dont get any output.

Does anyone has any advice ? :-)

Greeny
  • 1
  • Does this answer your question? [Returning 'c\_str' from a function](https://stackoverflow.com/questions/2657178/returning-c-str-from-a-function) – Botje Aug 13 '20 at 11:06
  • Return a `std::wstring` instead and only take the `.c_str()` when you call SQLExecDirect – Botje Aug 13 '20 at 11:07
  • `(SQLWCHAR)temp.c_str()` the fact you had to perform that cast to squelch a warning/eerror without actually fixing *anything* should be a strong hint where the problem lays. Further `SQLExecDirect` expects a terminated string for the statement, which clearly the address of a *single* `SQLWCHAR` is *not*. Perhaps return a `std::wstring` from your construction, then pass that's results `c_str()` as the second argument to `SQLExecDirect. – WhozCraig Aug 13 '20 at 11:07
  • So to understand it clearly --> I need to change my return function type to a wstring. Then i need to call the function, and assign the return value to a new variable (Lets call it SQLStatement), and the insert this variable into `SQLExecDirect(sqlStmtHandle, (&SQLStatement.c_str()), SQL_NTS)` – Greeny Aug 13 '20 at 11:36
  • ConstructQuery() should return SQLWCHAR* instead of SQLWCHAR. – StPiere Aug 13 '20 at 11:50
  • I got it to work by the following: `SQLExecDirect(sqlStmtHandle,(SQLWCHAR*)SQLStatement.c_str(), SQL_NTS)` with ConstructQuery() returning a wstring – Greeny Aug 13 '20 at 11:53

0 Answers0