Click here to Skip to main content
14,735,745 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to pass a query to MySQL via a C++ library. However, the query requires a const char* data type, so I tried...

//Initialization code ommitted.. includes declaration of conn, among others...

	const char* updateStr = ("update users set " + dbProperty + "='" + newValue + "' where id=" + ID + ";").c_str();
	mysql_query(conn, updateStr);


dbProperty, newValue, and ID are all parameters of the function. However, my code still not working properly. I know that the API is set up correctly because I can use mysql_query to pull data from the database without an issue. It's writing that's the problem. The above query syntax is correct though because I tried it in the server console window, and it worked fine. I wanted to make sure that the char* was appending correctly so I tried..

std::cout << updateStr << std::endl;

And all I got printed was a dash. What's going on? Why can't I build a string, convert it to const char*, and use it? Any ideas?

1 solution

You are building a temporary std::string object and ask it for its starting address (that's what c_str() does). As the string is temporary it will go out of scope as soon as control moves to the next statement. So, by the time mysql_query is executed, the string contents is already undefined.

Instead, assign the concattenation to a std::string object:
std::string updateCommand = ....
mysql_query (conn, updateCommand.c_str());
Sergey Alexandrovich Kryukov 19-Mar-13 15:07pm
nv3 19-Mar-13 15:18pm
Thanks, Sergey!
H.Brydon 19-Mar-13 23:15pm
me too...
nv3 20-Mar-13 2:52am
Thanks, H.Brydon!
RadXPictures 19-Mar-13 15:17pm
Thanks! I knew it had to be a simple solution for a pretty stupid question.. So thank you!
nv3 19-Mar-13 15:18pm
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900