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

Escaping strings with the C++ Mysql Driver

本文关键字:转义字符 字符串 转义 驱动程序 C++Mysql 使用      更新时间:2023-10-16

我在使用mysql c++驱动程序转义字符串时遇到问题。通过阅读mysql论坛,我发现了一个小例子,下面的方法似乎是正确的。然而,动态转换似乎不起作用。有人有什么见解吗?谢谢

p.S."conn"是我的Connection对象。它保证在这一点上被分配,所以它不是问题所在。

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

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!");
}

}

我知道这可能太晚了,但作为您的参考,转换失败了,因为您可能没有包括以下内容:

#include <mysql_connection.h>

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

在Linux Debian中,它位于以下位置:

/usr/include/mysql_connection.h

在某些情况下,它与mysql连接器一起提供。如果你把它包括在内,那么下变频效果很好:

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

希望它能帮助任何陷入同样问题的人。

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

不知道准备好的语句转义是如何进行的,因为我曾尝试在sql::connector

中使用它们,但没有成功