Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format SQL query in c++

Tags:

c++

sql

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

I'm sorry for didn't provide an example before. I want that 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

Thanks a lot.

like image 926
Frias Avatar asked Feb 28 '26 13:02

Frias


1 Answers

You can write your own pretty printer. In that case, it won't be any hard. Just replace things like the following:

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

etc.

Edit: as you don't code, here's a little version of this functionality.

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

So calling formatSql("SELECT MEMB.NAME, MEMB.AGE, AGE.GROUP FROM MEMB, AGE WHERE MEMB.AGE = AGE.AGE") gives you the desired result.

like image 194
Gabriel Avatar answered Mar 02 '26 13:03

Gabriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!