当前位置:网站首页>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;
}
边栏推荐
- 数据与信息资源共享平台(九)
- MySQL组合索引不被命中使用的情况
- A journey of database full SQL analysis and audit system performance optimization
- HALCON联合C#检测表面缺陷——仿射变换(二)
- 数据与信息资源共享平台(八)
- IPO can't cure Weima's complications?
- MySQL related -0416
- 关于String.format(String format, Object... args)
- Distributed Foundation
- Thread pool: a magic weapon for managing threads
猜你喜欢

【QPSK中频】基于FPGA的QPSK中频信号产生模块verilog设计

关于idea中src下 无法new一个package

Why is the video fusion cloud service easycvr cluster video event query invalid?

Vscode common plug-ins and configurations

That's great. The Ministry of industry and information technology has launched an internet account with a "one click unbinding" mobile phone number, which can be called an artifact

leetcode 130. Surrounded regions (medium)

Online questionnaire system based on php+web+mysql

Sealem Finance - a new decentralized financial platform based on Web3

Vulnhub's DC3

IP anti query domain name
随机推荐
数组、List、Set、Map、Properties依赖注入格式
我们对产业互联网的认识,还是困囿于互联网式的平台和中心的逻辑之中
Software project management 6.10 Cost budget
Question bank and simulation test of 2022 tea artist (intermediate) operation certificate examination
数据与信息资源共享平台(五)
Ribbon负载均衡策略
Can Huawei matepad become the secondary screen of your laptop?
PwnTheBox,Web:hello
Several reasons and solutions of virtual machine Ping failure
MySQL related -0416
About the college entrance examination
Operation of simulated examination platform for welder (primary) test questions in 2022
功能测试之设计语言测试:功能测试包含哪些测试?分别有什么作用
软件测试入门之软件测试的概念与过程(精辟内容)
UE4 getting started with bone animation
关于idea中src下 无法new一个package
【GMM+KDE】基于MATLAB的GMM和KDE核估计得目标跟踪仿真
2022 Shanghai safety officer C certificate operation certificate examination question bank simulated examination platform operation
IP anti query domain name
unity 代码为动画注册事件