使用Druid的SqlParser解析sql语句
druid
阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池
项目地址:https://gitcode.com/gh_mirrors/druid/druid
免费下载资源
·
d
解析sql
public Map<Integer, String> parseSql(String sql, DbType dbType) {
List<SQLStatement> statementList = SQLUtils.parseStatements(sql, dbType);
Map<Integer, String> sqlMap = new HashMap<Integer,String>();
for (SQLStatement stmt : statementList) {
if (stmt instanceof SQLInsertStatement) {
SQLInsertStatement insertStatement = (SQLInsertStatement) stmt;
List<SQLInsertStatement.ValuesClause> valuesClauses = insertStatement.getValuesList();
for (int i = 0; i < insertStatement.getColumns().size(); i++) {
String columnName = insertStatement.getColumns().get(i).toString();
SQLExpr columnValue = valuesClauses.get(0).getValues().get(i);
sqlMap.put(i,columnName);
}
}
}
return sqlMap;
}
变更sql
public static void main(String[] args) {
String sql ="INSERT INTO student ( user_name, email ) VALUES ( ?,? )";
List<SQLStatement> stmtList = SQLUtils.parseStatements(sql, DbType.mysql);
for (SQLStatement stmt : stmtList) {
if (stmt instanceof SQLInsertStatement) {
SQLInsertStatement insert = (SQLInsertStatement) stmt;
// 添加字段和值
insert.addColumn(SQLUtils.toSQLExpr("user_name_1", DbType.mysql));
// 创建新的值子句
SQLInsertStatement.ValuesClause values = insert.getValues();
values.addValue(SQLUtils.toSQLExpr("?", DbType.mysql));
// 输出修改后的SQL语句
String modifiedSql = SQLUtils.toMySqlString(insert);
System.out.println(modifiedSql);
}
}
}
GitHub 加速计划 / druid / druid
27.83 K
8.56 K
下载
阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池
最近提交(Master分支:3 个月前 )
f060c270 - 22 天前
1613a765
* Improve gaussdb ddl parser
* fix temp table 23 天前
更多推荐
已为社区贡献2条内容
所有评论(0)