在写质检规则的时候,有时需要在mysql规则库中查看修改之前写的sql规则
但是不幸的是在mysql规则库中的sql规则没有换行,非常难看,比如下面这个规则:
select 'nav_link" as tn, xxx as fid xxx xx from xx where xxx union all select xx as xx, from where ...
这样的格式真心是看不下去啊(捏一把汗),但是这种问题还常常遇到。
我想把sql语句拷贝下来之后手工换行,调整好格式,弄漂亮一些。
但是挨个去断行也非常麻烦,写个程序吧,干掉它。
对select from where 这一类关键词:换行+输出关键字+换行+留制表符。
对union 这一类关键词:换行+ 输出关键词就可以。
我把无换行的sql语句存在文件in.sql中,程序处理之后输出到out.sql文件中。
程序的结果和手工断行的效果一样一样的,【要想实现一些更细致的缩进可以再改程序。】
代码贴在附件,中文不能正确显示,体验不好,这里再贴一坨。
/* author: huangzhiqiang date: 2015-4-27 功能: 把in.sql文件中无换行的sql语句调整换行和缩进后输出到文件out.sql */ #include "stdafx.h"/*vs 环境中添加*/ #include<iostream> #include<string> #include<fstream> using namespace std; //keyStr1 需要前换行 #define N 7 string keyStr1[N] = { "creat", "delete", "drop", "update", "union", "order", "group"}; //keyStr2 需要前后换行 #define M 3 string keyStr2[M] = { "select", "from", "where" }; //转化string类型为大写字符 string toUpper(string str) { string strUp; for (int i = 0; i < str.length(); i++) { if (str[i] >= 'a'&&str[i] <= 'z') strUp.push_back(str[i] + 'A' - 'a'); else strUp.push_back(str[i]); } return strUp; } //判断是否是关键字,是哪种关键字 int judgeKey(string str) { for (int i = 0; i<N; i++) { if (str==keyStr1[i] || str==toUpper(keyStr1[i]) ) { return 1; } } for (int i = 0; i<M; i++) { if ( str==keyStr2[i] || str==toUpper(keyStr2[i]) ) { return 2; } } return 0; } int main() { string fileName,str; //无换行的sql语句的文件名为in.sql(和本程序在同一个目录下) fileName = "in.sql"; //从文件in.sql读入 freopen(&fileName[0], "r", stdin); //输出到文件out.sql freopen("out.sql", "w", stdout); while (cin >> str) { /*处理注释行*/ if (str.find("/*") != 4294967295) cout << endl << str; /*关键字1 如 union*/ else if ( judgeKey(str) == 1 ) { cout << endl; cout << str << " "; } /*关键字2 如 select*/ else if ( judgeKey(str) == 2 ) { cout << endl; cout << str << endl; cout << "\t"; } else cout << str << " "; } //关闭输入重定向 fclose(stdin); //关闭输出重定向 fclose(stdout); //打开文件,查看输出结果 system("out.sql"); } |