Oracle数据注释解析成查询语句

2023-08-30  本文已影响0人  power杏迪

场景

在实际的开发过程中我们可能会遇到,将一个表的字段转换成查询sql,例如:

select name as "姓名",age as "年龄" from acount

或者说根据sql将数据导出到excel中,这时候excel表头的注释不能是字段名称,要应用成相关字段的注释。如果字段少手写也是可以的,麻烦点就在与字段一多就很累。

解决问题

使用工具类OracleCommentParse就可以帮你解决这个头痛的问题。

public class OracleCommentParse {


    /**
     * 示例:
     * comment on column table.name IS '姓名';
     * comment on column table.age IS '年龄';
     * 解析后的sql:
     * select name as "姓名",age as "年龄" from table
     */
    public static void main(String[] args) {

        String fileName = "文件地址\\文件名称.txt";

        String table = "表名";

        LinkedHashMap<String, String> map = new LinkedHashMap<>();

        try {
            Scanner sc = new Scanner(new FileReader(fileName));
            //分隔符
            sc.useDelimiter(";");
            //按分隔符读取字符串
            while (sc.hasNext()) {
                String str = sc.next().toUpperCase();

                //判断表名字出现的位置
                int tableIndex = str.indexOf(table);

                //判断is最后出现的位置
                int isIndex = str.lastIndexOf("IS");
                //获取字段
                String column = str.substring(tableIndex + table.length() + 1, isIndex - 1);

                //获取字段注释
                String columnComment = str.substring(isIndex + 4, str.length() - 1);

                map.put(column, columnComment);

            }


            //拼接成查询sql
            StringBuilder sb = new StringBuilder();
            sb.append("select ");
            for (Map.Entry<String, String> entry : map.entrySet()) {

                sb.append(entry.getKey()).append(" as ").append("\"" + entry.getValue() + "\"").append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append(" from ").append(table);

            System.out.println(sb.toString());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}

示例:

提供一份txt文件,格式如下:

 comment on column table.name IS '姓名';
 comment on column table.age IS '年龄';

第一步 读取文件内容

工具类中 以 ; 为结尾读取第一行数据,
这时候读取的结果:comment on column table.name IS '姓名';

第二步 java的字符截取

// 获取表名出现的位置
int tableIndex = str.indexOf(table);

//判断is最后出现的位置  因为 IS是oracle注释语法的关键词
int isIndex = str.lastIndexOf("IS");

//获取字段 
String column = str.substring(tableIndex + table.length() + 1, isIndex - 1);

//获取字段注释
String columnComment = str.substring(isIndex + 4, str.length() - 1);

结果

select name as "姓名",age as "年龄" from table

工具类源码地址

地址:https://github.com/POWERzhangdi/jet_fighter/blob/main/src/main/java/com/jet/fighter/dbcomment/OracleCommentParse.java

上一篇 下一篇

猜你喜欢

热点阅读