为什么我的const char * cast不能正常工作? [英] Why isn't my const char* cast working correctly?

查看:113
本文介绍了为什么我的const char * cast不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过C ++库将查询传递给MySQL。但是,查询需要const char *数据类型,所以我尝试了...



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);

	mysql_close(conn);





dbProperty,newValue和ID是函数的所有参数。但是,我的代码仍然无法正常工作。我知道API设置正确,因为我可以使用mysql_query从数据库中提取数据而不会出现问题。它写的是'问题所在。上面的查询语法是正确的,因为我在服务器控制台窗口中尝试了它,并且它工作正常。我想确保char *正确添加,所以我尝试了..





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;





所有我打印的都是破折号。这是怎么回事?为什么我不能构建一个字符串,将其转换为const char *并使用它?任何想法?



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?

推荐答案

您正在构建一个临时的std :: string对象并询问它的起始地址(这就是c_str()的作用)。由于字符串是临时的,一旦控件移动到下一个语句,它就会超出范围。因此,在执行mysql_query时,字符串内容已经是未定义的。



相反,将连接分配给std :: string对象:

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());


这篇关于为什么我的const char * cast不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆