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;
    }

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐