使用 C++ Mysql 驱动程序转义字符串

tie*_*er1 4 c++ mysql string escaping

我在使用 mysql c++ 驱动程序转义字符串时遇到问题。我通过阅读 mysql 论坛找到了一个小例子,以下似乎是正确的方法。然而,动态演员阵容似乎不起作用。有人有任何见解吗?谢谢!

PS“conn”是我的连接对象。此时保证已分配,因此这不是问题。

编辑:添加类构造函数以完成代码示例。

DbConnector::DbConnector(const ns4__ServerHostResponse &response)
{
    try
    {
        driver = get_driver_instance();
            conn.reset(
                    driver->connect(boost::str(boost::format("tcp://%1%:3306") % response.DatabaseHostName), response.Username, response.Password));
            conn->setSchema(response.DbSchema);
            query << "";

    }
    catch(std::exception &ex)
    {
        throw CustomException(boost::str(boost::format("Unable to connect to database: %1%") % response.DbSchema), ex.what());
    }
    catch(...)
    {
        throw StokedTcpException(boost::str(boost::format("Unable to connect to database: %1%") % response.DbSchema));
    }
}

void DbConnector::EscapeString(std::string &s) {
if (conn)
{
    std::shared_ptr<sql::mysql::MySQL_Connection> mysqlConn(dynamic_cast<sql::mysql::MySQL_Connection*>(conn.get()));
    if (mysqlConn)
        s = mysqlConn->escapeString(s);
    else
        throw CustomException("Cannot allocate connection object to escape mysql string!");
}
Run Code Online (Sandbox Code Playgroud)

}

Æle*_*lex 5

我知道这可能太晚了,但供您参考,演员阵容失败,因为您可能没有包括以下内容:

#include <mysql_connection.h>
Run Code Online (Sandbox Code Playgroud)

不是C++ 中 sql::connector 的一部分,而是 MySQL 的底层 C 库。

在 Linux Debian 中,它可以在以下位置找到:

/usr/include/mysql_connection.h
Run Code Online (Sandbox Code Playgroud)

在某些情况下,它附带 mysql 连接器。如果包含它,那么向下转型就可以正常工作:

sql::mysql::MySQL_Connection * mysql_conn = dynamic_cast<sql::mysql::MySQL_Connection*>(con);
std::string escaped = mysql_conn->escapeString( query );
stmt->execute( escaped );
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助任何遇到同样问题的人。

编辑:实际上,您不应该转义查询,如上面的示例所示,而是转义特定的字符串。转义查询可能会转义值周围的单引号。

不知道准备好的语句到底是如何转义的,因为我尝试在 sql::connector 中使用它们但没有成功