编写Java代码,使用druid实现sql解析,sql为select语句,解析出select字段的依赖的表明.字段名
时间: 2024-02-27 12:57:55 浏览: 174
以下是使用druid实现sql解析,解析出select字段的依赖的表名和字段名的Java代码:
```java
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.*;
import com.alibaba.druid.sql.ast.statement.*;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.alibaba.druid.sql.parser.ParserException;
import java.util.ArrayList;
import java.util.List;
public class SqlParser {
public static void main(String[] args) {
String sql = "SELECT a.id, a.name, b.age FROM table_a a LEFT JOIN table_b b ON a.id = b.id WHERE a.gender = 'M'";
List<String> tableFields = parseSql(sql);
for (String tableField : tableFields) {
System.out.println(tableField);
}
}
public static List<String> parseSql(String sql) {
List<String> tableFields = new ArrayList<>();
try {
SQLStatement stmt = new MySqlStatementParser(sql).parseStatement();
if (stmt instanceof SQLSelectStatement) {
SQLSelectStatement selectStmt = (SQLSelectStatement) stmt;
SQLSelect select = selectStmt.getSelect();
List<SQLSelectItem> selectItems = select.getSelectList();
for (SQLSelectItem selectItem : selectItems) {
SQLExpr expr = selectItem.getExpr();
String tableField = parseExpr(expr);
if (tableField != null) {
tableFields.add(tableField);
}
}
}
} catch (ParserException e) {
e.printStackTrace();
}
return tableFields;
}
private static String parseExpr(SQLExpr expr) {
if (expr instanceof SQLPropertyExpr) {
SQLPropertyExpr propertyExpr = (SQLPropertyExpr) expr;
String owner = propertyExpr.getOwner().toString();
String column = propertyExpr.getName();
return owner + "." + column;
} else if (expr instanceof SQLIdentifierExpr) {
SQLIdentifierExpr identifierExpr = (SQLIdentifierExpr) expr;
String column = identifierExpr.getName();
return column;
} else if (expr instanceof SQLAllColumnExpr) {
return "*";
} else {
return null;
}
}
}
```
以上代码实现了将输入的SQL语句解析出所有select字段依赖的表名和字段名,并以"表名.字段名"的形式存储在一个List<String>中返回。例如,对于输入的SQL语句"SELECT a.id, a.name, b.age FROM table_a a LEFT JOIN table_b b ON a.id = b.id WHERE a.gender = 'M'",解析出的select字段依赖的表名和字段名为:
- table_a.id
- table_a.name
- table_b.age
注意,该代码仅支持解析MySQL语法的SQL语句,其他数据库的SQL语句需要根据具体语法进行相应修改。
阅读全文