Mysql查询字符串在查询c ++中不起作用

时间:2014-06-26 19:28:44

标签: c++ mysql

您好我在MySQL查询中收到字符串变量时遇到了问题我已经尝试了所有我不知道哪里出错我的任何建议。

string timestamp;     

if (mysql_query(MySQLConnection, "INSERT INTO tablemeters (timestamp,gasreading,electricreading)VALUES ('"+timestamp+"', 'gas', 'elec')"))

我得到的错误是:

  

menucurl.cpp:169:142:错误:无法将参数'2'的'std :: basic_string'转换为'const char *'为'int mysql_query(MYSQL *,const char *)'

2 个答案:

答案 0 :(得分:3)

您需要进行兼容的操作。 +不适用const char* 您应该使用std::ostringstream更好地格式化查询,并将最终结果作为const char*传递给mysql_query()方法:

std::string timestamp;     
std::ostringstream sqlStatement;

sqlStatement << "INSERT INTO 
                    tablemeters ( 
                       timestamp ,
                       gasreading,
                       electricreading
                    )
                 VALUES   
                    ('" << timestamp << ',' <<
                     '\'' << gas << "'," <<
                     '\'' << elec << "')";
// Check the literal text of the SQL statement before passing it to mysql_query()
typedef std::cout logger;
logger << "Executing SQL command: \"" << sqlStatement.str()  "\"" << std::endl;

if (mysql_query(MySQLConnection, sqlStatement.str().c_str())) {
    // ...
}

答案 1 :(得分:1)

尝试这样的事情:

std::string timestamp;
std::string query = "INSERT INTO tablemeters (timestamp,gasreading,electricreading) VALUES ('"+timestamp+"', 'gas', 'elec')";

if (mysql_query(MySQLConnection, query.c_str()))...