cannot convert ‘std::__cxx11::basic_string<char>’ to ‘const char*’ for argument ‘2’ to ‘PGresult*

I have ubuntu 18.04 and postgresql 14. I have a c++ code below.
Im a executing a query and want to get one specfic column.
Here is my code:

PGconn *conn;
PGresult *ress;
int rec_count;
int row;
int col;

conn = PQconnectdb("dbname=usr host=localhost user=vdmin password=mypwd");

if (PQstatus(conn) == CONNECTION_BAD) {
puts("We were unable to connect to the database");
exit(0);
}

unique_id = root.get("UniqueID", "null" ).asString();


if(unique_id != "null"){

ress = PQexec(conn,"SELECT name FROM users WHERE unique_id='"+unique_id+"' and command_flag = 0");

while (res->next()) {


name = res->getString("name");


}

ıt doesnt work. I got an error
error: cannot convert ‘std::__cxx11::basic_string<char>’ to ‘const char*’ for argument ‘2’ to ‘PGresult* PQexec(PGconn*, const char*)’



How can i solve it?
Last edited on
error: cannot convert ‘std::__cxx11::basic_string<char>’ to ‘const char*’ for argument ‘2’ to ‘PGresult* PQexec(PGconn*, const char*)’


std::__cxx11::basic_string<char> means std::string.

const char* is how you pass "C strings" (i.e. as a pointer to the first element in a null-terminated char array).

PGresult* PQexec(PGconn*, const char*) this says the second argument should be a C string (const char*).


When you write a string literal like "SELECT name FROM users" that will give you a C string.

"SELECT name FROM users WHERE unique_id='"+unique_id+"' and command_flag = 0" is however not a C string. It is a std::string (because unique_id is a std::string and using + to concatenate a std::string and a C string will give you a std::string).


To get a C string from a std::string you can use the c_str() member function.

 
ress = PQexec(conn,("SELECT name FROM users WHERE unique_id='"+unique_id+"' and command_flag = 0").c_str());

Last edited on
I cannot avoid feeling a bit uneasy when I see strings being inserted directly inside a SQL query like this. You need to be a bit careful, especially if the strings are inputted from the user, because you might have to escape certain characters (e.g. ') and it could enable a way to do "SQL injections" if you're not careful. https://en.wikipedia.org/wiki/SQL_injection

I have no prior experience with PostgreSQL but I have used other SQL database systems in other languages and there it is often possible to write placeholders in the query and pass in the values separately. This can be done more safely because the strings can be escaped properly to avoid SQL injections and other problems. A quick search seems to suggest you can accomplish something similar in PostgreSQL using either PQexecParams or PQprepare/PQexecPrepared.
Last edited on
thank you so much. my problem solved.
Topic archived. No new replies allowed.