15-SQL解析 - jsqlparser
JSqlParser 是一个用于解析 SQL 查询语句的 Java 库。
它可以将 SQL 查询语句解析成易于操作的数据结构,使你能够分析、修改或优化查询。
github:https://github.com/JSQLParser/JSqlParser
依赖
xml
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>4.3</version>
</dependency>
使用jsqlparser创建MySQL建表语句
java
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.create.table.ColDataType;
import net.sf.jsqlparser.statement.create.table.ColumnDefinition;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class CreateTableDemo {
public static void main(String[] args)throws Exception {
CreateTable createTable = new CreateTable();
// 设置表名
Table table = new Table("t_one");
createTable.setTable(table);
// 定义字段
// id
ColDataType bigint = new ColDataType("BIGINT");
bigint.setArgumentsStringList(Collections.singletonList("20"));
ColumnDefinition id = new ColumnDefinition("id", bigint);
id.setColumnSpecs(Arrays.asList("UNSIGNED", "NOT NULL", "PRIMARY KEY", "AUTO_INCREMENT", "COMMENT '主键'"));
// name
ColDataType varchar = new ColDataType("VARCHAR");
varchar.setArgumentsStringList(Collections.singletonList("64"));
ColumnDefinition name = new ColumnDefinition("name", varchar);
name.setColumnSpecs(Collections.singletonList("COMMENT '名字'"));
// age
ColDataType anInt = new ColDataType("INT");
ColumnDefinition age = new ColumnDefinition("age", anInt);
age.setColumnSpecs(Collections.singletonList("COMMENT '仙人年龄'"));
// 设置字段
List<ColumnDefinition> columnDefinitionList = new ArrayList<>();
columnDefinitionList.add(id);
columnDefinitionList.add(name);
columnDefinitionList.add(age);
createTable.setColumnDefinitions(columnDefinitionList);
// 设置IF NOT EXISTS
createTable.setIfNotExists(true);
// 设置引擎、字符集、排序规则
createTable.setTableOptionsStrings(Arrays.asList("ENGINE = InnoDB", "CHARACTER SET = utf8mb4", "COLLATE = utf8mb4_general_ci"));
// 打印建表语句
System.out.println(createTable);
}
}
结果:
sql
CREATE TABLE IF NOT EXISTS t_one (id BIGINT (20) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT '主键', name VARCHAR (64) COMMENT '名字', age INT COMMENT '仙人年龄') ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci