Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

JSqlParser를 사용하여 CREATE TABLE 문에 기본 키 추가

파서는 일련의 단어/문장의 문법을 이해하고 구문 트리 표현을 생성하는 프로그램입니다. 프로그래밍 언어, 자연어 처리, SQL 등 다양한 분야에서 사용되고 있습니다. Parser의 사용법을 보여주기 위해 이 튜토리얼에서는 오픈 소스 JSqlParser를 참조할 것입니다.

JSql파서

JSqlParser는 Github에서 오픈 소스로 제공되는 SQL 문 파서입니다. SQL 문을 구문 분석하고 Java 클래스의 계층 구조로 변환합니다. 다음 예에서는 JSqlParser를 사용하여 CREATE TABLE 문을 구문 분석합니다. CREATE TABLE 문을 구문 분석하고 여기에 기본 키를 추가하는 Java 프로그램을 작성해 보겠습니다.

CREATE TABLE 문

CREATE TABLE College_db.Students (
 Student_id int,
 Name varchar(255),
 Course varchar(255),
 Join_date DATE
);

위의 CREATE TABLE 문에서 Student_id 열을 추가하려고 합니다. 기본 키로 사용됩니다.

JSqlParser를 사용하여 CREATE TABLE SQL을 구문 분석하는 Java 프로그램

1단계:JSqlParser를 종속성으로 추가

JSqlParser를 종속성으로 추가하기 위해 Maven 프로젝트를 생성 중입니다. pom.xml 파일에 아래 종속성을 추가해 보겠습니다.

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

2단계:입력 CREATE TABLE 문을 변수에 할당

이는 기본 키가 없는 입력 CREATE TABLE 문입니다. 개행 문자 \n은 선택 사항입니다. 전체 SQL을 한 줄로 제공할 수도 있습니다. 가독성을 위해 여러 줄로 입력을 제공합니다.

String createTableSql = "CREATE TABLE College_db.Students (\n" +
 " Student_id int,\n" +
 " Name varchar(255),\n" +
 " Course varchar(255),\n" +
 " Join_date DATE\n" +
 ");";

3단계:JSqlParser를 사용하여 SQL 구문 분석

파서 유틸리티 클래스 CCJSqlParserUtil 사용 , CREATE TABLE sql의 인수로 구문 분석 메소드를 호출합니다.

Statement createTable = CCJSqlParserUtil.parse(createTableSql);

Parse 메소드를 실행한 후, Statement 객체 createTable은 아래와 같은 Java 클래스의 계층구조를 갖게 됩니다.

JSqlParser를 사용하여 CREATE TABLE 문에 기본 키 추가 Java 클래스의 계층 구조로 JSqlParser 출력

4단계:파서 출력 탐색

구문 분석 메소드가 성공적으로 실행되면 CREATE TABLE 문에 대한 모든 정보를 얻을 수 있습니다. 문의 데이터베이스/테이블 이름과 열 정의를 가져옵니다. 또한 create table 문에서 데이터베이스와 테이블 이름을 변경하고 있습니다.

System.out.println("Table Name from query: " + ((CreateTable) createTable).getTable().getName());
System.out.println("Database Name from query: " + ((CreateTable) createTable).getTable().getSchemaName());
System.out.println("\nColumns in the given insert query");
System.out.println("---------------------------------\n");
for(ColumnDefinition col: ((CreateTable) createTable).getColumnDefinitions())
{
 System.out.println(col.getColumnName() + " - " + col.getColDataType().toString());
}
//Changing the DB and table name
((CreateTable) createTable).getTable().setSchemaName("College_db_bk");
((CreateTable) createTable).getTable().setName("Students_bkup");

5단계:기본 키 제약조건을 인덱스로 생성

Check 제약 조건, Exclude 제약 조건, Foreign Key 및 Named 제약 조건과 같은 다양한 인덱스를 Sql에 설정할 수 있습니다. 기본 키의 경우 아래와 같이 명명된 제약 조건을 생성해야 합니다.

//Creating Primary Key constraint
NamedConstraint namedConstraint = new NamedConstraint();
namedConstraint.setType("PRIMARY KEY");
//Adding column names for the Primary Key
List<Index.ColumnParams> columns = new ArrayList<>();
Index.ColumnParams columnParams = new Index.ColumnParams("Student_id");
columns.add(columnParams);
//Setting columns in the Primary Key constraint
namedConstraint.setColumns(columns);

Student_id의 기본 키를 인덱스의 Named 제약 조건으로 설정해 보겠습니다.

//Setting the Primary Key constraint in Index list
List<Index> indexList = new ArrayList<>();
indexList.add(namedConstraint);

6단계:CREATE TABLE 문에 인덱스 설정

Primary Key를 사용하여 CREATE table 문이 생성되도록 create table에 index 목록을 아래와 같이 설정해야 합니다.

((CreateTable) createTable).setIndexes(indexList);

CREATE TABLE SQL에 기본 키를 추가하는 완전한 Java 프로그램

import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.create.table.ColumnDefinition;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import net.sf.jsqlparser.statement.create.table.Index;
import net.sf.jsqlparser.statement.create.table.NamedConstraint;
import java.util.ArrayList;
import java.util.List;
public class AddPrimaryKey {
 public static void main(String[] args) {
 System.out.println("Adding Primary key in the CREATE TABLE statement");
 System.out.println("-------------------------------------\n");
 //Assign the input CREATE TABLE sql
 String createTableSql = "CREATE TABLE College_db.Students (\n" +
 " Student_id int,\n" +
 " Name varchar(255),\n" +
 " Course varchar(255),\n" +
 " Join_date DATE\n" +
 ");";
 try {
 //Parsing Create table statement using JSqlParser
 Statement createTable = CCJSqlParserUtil.parse(createTableSql);
 //Getting the table and database name from Create table
 System.out.println("Table Name from query: " + ((CreateTable) createTable).getTable().getName());
 System.out.println("Database Name from query: " + ((CreateTable) createTable).getTable().getSchemaName());
 System.out.println("\nColumns in the given insert query");
 System.out.println("---------------------------------\n");
 for (ColumnDefinition col : ((CreateTable) createTable).getColumnDefinitions()) {
 System.out.println(col.getColumnName() + " - " + col.getColDataType().toString());
 }
 //Changing the DB and table name
 ((CreateTable) createTable).getTable().setSchemaName("College_db_bk");
 ((CreateTable) createTable).getTable().setName("Students_bkup");
 //Creating Primary Key constraint
 NamedConstraint namedConstraint = new NamedConstraint();
 namedConstraint.setType("PRIMARY KEY");
 //Adding column names for the Primary Key
 List<Index.ColumnParams> columns = new ArrayList<>();
 Index.ColumnParams columnParams = new Index.ColumnParams("Student_id");
 columns.add(columnParams);
 //Setting columns in the Primary Key constraint
 namedConstraint.setColumns(columns);
 //Setting the Primary Key constraint in Index list
 List<Index> indexList = new ArrayList<>();
 indexList.add(namedConstraint);
 //Setting the indexes in Create table statement
 ((CreateTable) createTable).setIndexes(indexList);
 System.out.println("New CREATE TABLE statement with Primary Key");
 System.out.println("---------------------------------");
 System.out.println(createTable + ";");
 } catch (JSQLParserException e) {
 throw new RuntimeException(e);
 }
 }
}

출력

아래에 표시된 것처럼 Student_id의 기본 키를 사용하여 새로운 CREATE TABLE이 생성됩니다. 또한 데이터베이스 및 테이블 이름이 College_db_bk.Students_bkup으로 변경됩니다.

Adding Primary key in the CREATE TABLE statement
-------------------------------------
Table Name from query: Students
Database Name from query: College_db
Columns in the given insert query
---------------------------------
Student_id - int
Name - varchar (255)
Course - varchar (255)
Join_date - DATE
New CREATE TABLE statement with Primary Key
---------------------------------
CREATE TABLE College_db_bk.Students_bkup (Student_id int, 
Name varchar (255), 
Course varchar (255), 
Join_date DATE, 
PRIMARY KEY (Student_id));

추천 기사

  • Apache Hive 파서 예시