Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping strings with the C++ Mysql Driver

I'm having trouble escaping strings with the mysql c++ driver. I found a small example by reading through the mysql forums and the following appears to be the correct way to do it. However, the dynamic cast does not appear to be working. Does anybody have any insight? Thanks!

P.S. "conn" is my Connection object. It is guaranteed to be allocated at this point so it is not the problem.

EDIT: Adding class constructor to complete the code example.

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

}

like image 391
tier1 Avatar asked Oct 18 '25 01:10

tier1


1 Answers

I know this is probably way too late, but for your reference, the cast failed because you were probably not including the following:

#include <mysql_connection.h>

Which is not part of sql::connector in C++, but the underlying C library for MySQL.

In Linux Debian it's found under:

/usr/include/mysql_connection.h

And in some cases it's shipped with mysql connector. If you include it, then the downcast works fine:

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

Hope it helps anybody stuck in the same kind of problem.

EDIT: Actually, you shouldn't be escaping the query as the example shows above, but the specific strings. Escaping a query will probably escape the single quotes around values.

Don't know how exactly prepared statement escapes, as I've tried using them with no success in sql::connector

like image 71
Ælex Avatar answered Oct 19 '25 15:10

Ælex