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

Mysql query string not working in query c++

本文关键字:查询 工作 字符串 Mysql c++      更新时间:2023-10-16

嗨,我有问题得到一个字符串变量到我的MySQL查询我已经尝试了一切,我不知道我在哪里出错任何建议,请。

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

获取错误是:

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

您需要具有兼容的操作。+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())) {
    // ...
}

试试这样:

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