Question

I'm building a class wrapper for the mysql c api, specifically at the moment for mysql_real_escape_string and I don't think I'm doing it quite right.

this is what I have for the function:

std::string Database::EscapeString(const char *pStr)
{
    char *tStr = new char[strlen(pStr)*2+1];
    mysql_real_escape_string(m_sqlCon, tStr, pStr, strlen(pStr));
    string retStr(tStr);
    delete [] tStr;
    return retStr;
}

I tried running this through but it did not perform as expected and ended in mysql errors.

Was it helpful?

Solution

Looks good to me. I suspect your database problem is elsewhere.

There's an easy way to check: temporarily replace Database::EscapeString with a dummy function, i.e.

std::string Database::EscapeString(const char *pStr) {return string(pStr);}

Then see if you get the same errors.

Edit: Not knowing exactly what the error is, or what the query causing it is, it's tough to narrow down the problem. Here are some things to try:

A) Just get rid of all characters that would need to be escaped. It'll put bogus data into the database, but hopefully you're just testing anyways:

std::string Database::EscapeString(const char *pStr) {
    string result;
    while (*pStr) {
        if (strchr("\"'\r\n\t",*pStr))
        {
            //bad character, skip
        }
        else
        {
            result.push_back(*pStr);
        }
        ++pStr;
    }
    return result;
}

B) Look for errors elsewhere. Is Database::Execute coded well? Maybe it does a snprintf internally with a hardcoded buffer size (which you may be exceeding)

C) Try taking your debug output and entering it straight into the mysql client program (don't forget to put a semicolon at the end). Same error?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top