sql语法检测
·
maven配置:
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>4.2</version>
</dependency>
用 jsqlparser可以限定输入哪种DML sql语句,如只限定select查询语句,用执行计划可以校验sql语法错误,如下:
public SqlCheckRspVo sqlCheck(SqlCheckReqVo sqlCheckReqVo) {
SqlCheckRspVo sqlCheckRspVo = new SqlCheckRspVo();
if(!sqlCheckReqVo.getSql().contains("$")){
return new SqlCheckRspVo(false,"sql中没有添加$");
}
sqlCheckReqVo.setSql(sqlCheckReqVo.getSql().trim());
if(sqlCheckReqVo.getSql().endsWith(";")){
sqlCheckReqVo.setSql(sqlCheckReqVo.getSql().substring(0,sqlCheckReqVo.getSql().length()-1));
}
for(AddReqVo.TableInfo tableInfo : sqlCheckReqVo.getRuleTables()) {
String sql = sqlCheckReqVo.getSql().replace("$",tableInfo.getTableName());
sqlCheckRspVo = sqlparse(sql);
if(sqlCheckRspVo.getCheckResult() == false){
return sqlCheckRspVo;
}
SqlSession sqlSession = null;
PreparedStatement pst ;
try {
sqlSession = getNativeSqlSession();
Connection dbCon = sqlSession.getConnection();
pst = dbCon.prepareStatement("explain plan for " +sql);
pst.executeUpdate();
pst.close();
} catch (SQLException e) {
sqlCheckRspVo.setCheckResult(false);
sqlCheckRspVo.setErrorLog(ExceptionUtils.getStackTrace(e));
return sqlCheckRspVo;
} finally {
if (null != sqlSession) {
closeNativeSqlSession(sqlSession);
}
}
}
return sqlCheckRspVo;
}
public SqlCheckRspVo sqlparse(String sqlContent){
SqlCheckRspVo sqlCheckRspVo = new SqlCheckRspVo();
try {
Statement parse = CCJSqlParserUtil.parse(sqlContent);
if(parse instanceof Select){
sqlCheckRspVo.setCheckResult(true);
}else{
sqlCheckRspVo.setCheckResult(false);
sqlCheckRspVo.setErrorLog("只能输入select语句");
}
}catch (Exception e){
sqlCheckRspVo.setCheckResult(false);
sqlCheckRspVo.setErrorLog(ExceptionUtils.getStackTrace(e));
}
return sqlCheckRspVo;
}
更多推荐
已为社区贡献2条内容
所有评论(0)