【问题标题】:Escaping strings with the C++ Mysql Driver使用 C++ Mysql 驱动程序转义字符串
【发布时间】:2013-06-25 21:17:52
【问题描述】:

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

附: “conn”是我的 Connection 对象。保证在此时分配,所以不是问题。

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

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

}

【问题讨论】:

  • 仍然没有看到“conn”的声明...?
  • 这是一个 shared_ptr。查看 conn.reset() 行。
  • 在我的标题中,它是 std::shared_ptr<:connection> conn;
  • sql::mysql::MySQL_Connection 是合法的向下转换,还是拼写错误?我很难找到 mysql 文档。有必要吗?你能用你有的 sql::Connection 调用 escapeString 吗?
  • 我相信这是一个合法的沮丧。 sql::Connection 类中没有 escapeString 函数。这是我尝试的第一件事......

标签: c++ mysql string escaping


【解决方案1】:

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

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

希望它能帮助遇到同样问题的人。

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

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

【讨论】:

  • 谢谢亚历克斯。我意识到我应该一直使用准备好的语句,所以我走了那条路。不过我绝对可以用这个
猜你喜欢
  • 1970-01-01
  • 2013-01-30
  • 2012-02-05
  • 1970-01-01
  • 2015-09-08
  • 2010-11-30
  • 1970-01-01
  • 2012-03-11
相关资源
最近更新 更多