Format SQL query in C ++

I was wondering if there is something that I can use in C ++, like the "sqlparse" module in Python , to format my query. Do you know what I can use?

Sorry, did not provide an example before. I want something like this:

SELECT MEMB.NAME, MEMB.AGE, AGE.GROUP FROM MEMB, AGE WHERE MEMB.AGE = AGE.AGE

Become this:

SELECT MEMB.NAME,
       MEMB.AGE,
       AGE.GROUP
FROM   MEMB,
       AGE
WHERE  MEMB.AGE = AGE.AGE

Many thanks.

+3
source share
1 answer

You can write your own beautiful printer. In this case, it will not be difficult. Just replace things like:

"FROM" -> "\nFROM"
"WHERE" -> "\nWHERE"
"," -> ",\n\t"
"AND" -> "AND\n\t"
"OR" -> "OR\n\t"

and etc.

Edit: since you are not coding, here is a small version of this function.

#include <string>
using std::string; /* put these lines in the top of your file */

string replace(string a, string b, string c) {
    unsigned x;
    for(x = a.find(b); x != string::npos;) {
        a.erase(x, b.length());
    a.insert(x, c);
    }
    return a;
}




string formatSQL(string sql) {

    replace(sql, "FROM", "\nFROM");
    replace(sql, "WHERE", "\nWHERE");
    replace(sql, "," , ",\n\t");
    replace(sql, "AND", "AND\n\t");
    replace(sql, "OR", "OR\n\t");
}

Thus, the call formatSql("SELECT MEMB.NAME, MEMB.AGE, AGE.GROUP FROM MEMB, AGE WHERE MEMB.AGE = AGE.AGE")gives the desired result.

+2
source

All Articles