当前位置: 首页 > 工具软件 > JSqlParser > 使用案例 >

JSqlParser使用

闻人景澄
2023-12-01

JSqlParser使用

什么是JSqlParser

JSqlParser 是一个 SQL 语句解析器。
它将 SQLs 转换为可遍历的 Java 类层次结构。

如何使用JSqlParser

1.添加依赖

<dependency>
	<groupId>com.github.jsqlparser</groupId>
	<artifactId>jsqlparser</artifactId>
	<version>4.2</version>
</dependency>

2.解析创建表sql

/**
    * jSqlParser解析创建表sql
    *
    * @param path
    * @return
    * @throws JSQLParserException
    */
private List<Table>  parseCreateTables(String path) throws JSQLParserException {
    String lines = FileUtil.readString(path, StandardCharsets.UTF_8);
    String[] stats = lines.split(";\n");

    List<Table> tables = Lists.newArrayList();
    Table currTable;
    for (String statement : stats) {
        if (replaceBr(statement).isEmpty()) {
            continue;
        }
        Statement parsed = CCJSqlParserUtil.parse(statement, null);
        if (parsed instanceof CreateTable) {
            CreateTable createTableParsed = (CreateTable) parsed;
            String tableName = replaceRightDot(createTableParsed.getTable().getName());

            Table table = new Table();
            table.tableName = tableName;
            tables.add(table);
            currTable = table;

            List<ColumnDefinition> columns = createTableParsed.getColumnDefinitions();
            for (ColumnDefinition column : columns) {
                String columnName = replaceRightDot(column.getColumnName());
                String columnType = column.getColDataType().getDataType();
                String columnComment = "";
                Boolean commentFound = false;
                for (String spec : column.getColumnSpecs()) {
                    if (commentFound) {
                        columnComment = replaceSymbol(spec, "'").trim();
                        break;
                    }
                    if ("COMMENT".equalsIgnoreCase(spec)) {
                        commentFound = true;
                    }
                }

                Field field = new Field();
                field.name = columnName;
                field.comment = columnComment;
                currTable.fields.add(field);
            }
        }

        System.out.println(tables);
    }
    return tables;
}

参考

JSqlParser github

JSqlParser wiki

 类似资料: