java截取sql列_java – JSqlParser – 从Column获取表名
时间: 2023-10-19 09:32:50 浏览: 98
你可以使用JSqlParser库来解析SQL语句,从Column对象中获取表名。以下是一个简单的示例代码:
```
String sql = "SELECT t1.id, t2.name FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id";
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
SelectBody selectBody = select.getSelectBody();
if (selectBody instanceof PlainSelect) {
PlainSelect plainSelect = (PlainSelect) selectBody;
List<SelectItem> selectItems = plainSelect.getSelectItems();
for (SelectItem selectItem : selectItems) {
if (selectItem instanceof SelectExpressionItem) {
SelectExpressionItem selectExpressionItem = (SelectExpressionItem) selectItem;
Expression expression = selectExpressionItem.getExpression();
if (expression instanceof Column) {
Column column = (Column) expression;
String tableName = column.getTable().getName();
String columnName = column.getColumnName();
System.out.println("Table: " + tableName + ", Column: " + columnName);
}
}
}
}
```
这个示例代码将输出以下内容:
```
Table: table1, Column: id
Table: table2, Column: name
```
注意,这个示例代码只适用于简单的SELECT语句,如果你需要处理更复杂的SQL语句,你需要进行更多的判断和处理。
阅读全文