当前位置:网站首页>Project training 12 - parsing SQL statements for creating tables

Project training 12 - parsing SQL statements for creating tables

2022-06-10 23:14:00 ScarlettWX

   The administrator can create a new database to store user information and create tables on the administrator side , You can also select an existing user database to create a table . The previous interface allows the administrator to determine which columns are available , Then fill in the Chinese name, Chinese description and the selected type for these columns . The creation of tables here is not very flexible , You cannot select the field length at will and cannot create multiple primary keys and foreign keys . The function of the new iteration is to allow administrators to use SQL Statement table building . call SQL Sentences are not difficult , But the system database needs to store the field name of the new table 、 Type and introduction , The difficulty lies in how to decompose SQL Statement to get the field name and field type .
  SQL Statement to String Types exist , There may be multiple spaces in the table creation statement , Therefore, using spaces as separators cannot successfully split field names and field types , And there may be something similar “primary key”、“aoto_increment”、“not null” And other supplementary attributes disturb the division of the first column and the second column . It occurred to me that in the end, you still need a tool package to create a table SQL Decomposition of . There are almost no tutorials for decomposing table building statements on the Internet , I decompose according to a select The tutorial of the statement writes the decomposition create Code for statement . The project needs to be introduced druid Package dependency , Use the class and method decomposition of this package SQL. The dependency code is as follows :

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

Project application.properties It also needs to be changed :

server.port=8080
spring.datasource.name==druid
spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.url=jdbc:mysql://localhost:3306/databaseName?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.username=root
spring.datasource.druid.password=xxxxxxxx
spring.datasource.druid.filters=stat

   The first thing I want to know is create table Statement and the corresponding field type and field description .druid There are different types in the package SQL The class of the statement , For example, the new database statement should use SQLCreateDatabaseStatement type , The drop index table statement should use SQLDropIndexStatement type , New tables should use SQLCreateTableStatement type , Using the wrong type will not resolve to the correct result . I started by parsing select Statement tutorial uses the wrong object , The field name and type have not been resolved . and druid Packages can also parse statements from different databases , Pay attention to this , Comparison of different databases SQL There are some grammatical differences in the sentence . The first step in parsing is to declare a SQLStatementParser Object of type parser, I'm using MySQL database , therefore new The subtype of the output is MySqlStatementParser. The second step is to declare a SQLCreateTableStatement object sqlCreateTableStatement be equal to parser.parseCreateTable().parser The method called also corresponds to create table Type statements , For other operations, use the corresponding parse Method . Step 3 declare a SQLObject Type of List object sqlObjects Storage sqlCreateTableStatement The children of , These sub objects store the information of each field . Then use a for Loop processing sqlObjects Each sub object in the . Judge before you get specific information sqlObjects Whether it is after instantiation SQLColumnDefinition type , Column definition object . If it is , Through columnDefinition.getNameAsString() Get the field name ,columnDefinition.getDataType().getName() Get field type ,(String) ((SQLCharExpr) columnDefinition.getComment()).getValue() Get the field description . Note that the field type does not include the field length in parentheses . Use ((SQLIntegerExpr) arguments.get(0)).getNumber().toString() Get the length of the field , Then the complete field type is obtained through string splicing . The information obtained has a meta object , One of the loops meta Type of List object . Recirculation execution inserts DBID_CID_META The operation of the table . This completes the parsing and table creation SQL Statement operation . The specific code is as follows :

    public void assembleMeta(List<Meta> metaList, String sql) {
    
        SQLStatementParser parser = new MySqlStatementParser(sql);
        SQLCreateTableStatement sqlCreateTableStatement=parser.parseCreateTable();
        List<SQLObject> sqlObjects = sqlCreateTableStatement.getChildren();

        for (SQLObject sqlObject : sqlObjects) {
    
            if (sqlObject instanceof SQLColumnDefinition) {
    
                SQLColumnDefinition columnDefinition = ((SQLColumnDefinition) sqlObject);
                Meta meta=new Meta();
                meta.setEN(columnDefinition.getNameAsString());
                System.out.println(" from SQL Field name obtained in :"+meta.getEN());
                String metaType=columnDefinition.getDataType().getName();
                List<SQLExpr> arguments = columnDefinition.getDataType().getArguments();
                if (!CollectionUtils.isEmpty(arguments)) {
    
                    metaType=metaType+"("+((SQLIntegerExpr) arguments.get(0)).getNumber().toString()+")";
                }
                meta.setCN(metaType);
                System.out.println(" from SQL Field types obtained in :"+meta.getCN());
                if (columnDefinition.getComment() != null) {
    
                    meta.setDes((String) ((SQLCharExpr) columnDefinition.getComment()).getValue());
                    System.out.println(" from SQL Field description obtained in :"+meta.getDes());
                }else{
    
                    meta.setDes(" No introduction !");
                    System.out.println(" from SQL Field description obtained in :"+meta.getDes());
                }
                meta.setZhengze("F");
                metaList.add(meta);
            }else{
    
                System.out.println(" The type is still wrong !");
            }
        }
    }

controller Layer calling code :

    @ResponseBody
    @RequestMapping(value = "/createSQL",method = RequestMethod.POST)
    public Map<String, Object> createSQL(HttpServletRequest req) throws SQLException {
    
        Map<String, Object> map = new HashMap<>();
        int DBid =Integer.parseInt(req.getParameter("DBid").trim());
        System.out.println(" User database number :"+DBid);
        int Cid =Integer.parseInt(req.getParameter("Cid").trim());
        System.out.println(" New table number :"+Cid);
        String sql =req.getParameter("sql").trim();

        int ctsql=chartService.sqlCreateTable(DBid,sql);
        System.out.println(" Successfully created a table in the user database !");

        List<Meta> metaList=new ArrayList<>();
        getFromSQL g=new getFromSQL();
        g.assembleMeta(metaList,sql);
        int [] um=new int[metaList.size()];
        int judge=0;
        for(int i=0; i<metaList.size(); i++){
    
            um[i]=metaService.insertMeta(DBid,Cid,metaList.get(i).getEN(),metaList.get(i).getCN(),metaList.get(i).getDes());
            System.out.println("um["+i+"]="+um[i]);
            if(um[i]!=0)
                judge=1;
        }

        if (ctsql==0&&judge==0) {
    
            map.put("state", true);
            map.put("msg", " Use SQL The table was built successfully !");
        } else {
    
            map.put("state", false);
            map.put("msg", " Failed to create table ! Please check SQL Sentence grammar problems !");
        }
        return map;
    }
原网站

版权声明
本文为[ScarlettWX]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102201137557.html