当前位置:网站首页>SQL syntax detection

SQL syntax detection

2022-06-22 17:53:00 Stay for love

maven To configure :

        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>4.2</version>
        </dependency>

use jsqlparser You can limit what kind of DML sql sentence , If only limited select Query statement , You can verify with the execution plan sql Grammar mistakes , as follows :

    public SqlCheckRspVo sqlCheck(SqlCheckReqVo sqlCheckReqVo) {
        SqlCheckRspVo sqlCheckRspVo = new SqlCheckRspVo();
        if(!sqlCheckReqVo.getSql().contains("$")){
           return new SqlCheckRspVo(false,"sql Not added in $");
        }
        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(" Input only select sentence ");
            }
        }catch (Exception e){
            sqlCheckRspVo.setCheckResult(false);
            sqlCheckRspVo.setErrorLog(ExceptionUtils.getStackTrace(e));
        }
        return sqlCheckRspVo;
    }

原网站

版权声明
本文为[Stay for love]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221507399071.html