开发者

Format SQL query in c++

开发者 https://www.devze.com 2023-03-04 05:02 出处:网络
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 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.开发者_如何学JAVAAGE

Become this:

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

Thanks a lot.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号