Java
 Computer >> コンピューター >  >> プログラミング >> Java

JSqlParser を使用した CREATE TABLE ステートメントへの主キーの追加

パーサーは、一連の単語/文の文法を理解し、構文ツリー表現を生成するプログラムです。プログラミング言語、自然言語処理、SQL などの多くの分野で使用されています。パーサーの使用法を示すために、このチュートリアルではオープンソースの 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 を 1 行で記述することもできます。読みやすくするために、入力を複数行で記載しています。

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 の引数を指定して parse メソッドを呼び出しています。

Statement createTable = CCJSqlParserUtil.parse(createTableSql);

parse メソッドを実行すると、Statement オブジェクト createTable は以下のような Java クラスの階層を持ちます。

JSqlParser を使用した CREATE TABLE ステートメントへの主キーの追加 Java クラスの階層としての JSqlParser 出力

ステップ 4 :パーサーの出力を調べる

parse メソッドが正常に実行されると、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 :主キー制約をインデックスとして作成する

チェック制約、除外制約、外部キー、名前付き制約など、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 の主キーをインデックスの名前付き制約として設定しましょう。

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

ステップ 6:CREATE TABLE ステートメントでインデックスを設定する

主キーを使用して CREATE table ステートメントが生成されるように、create table に以下のようにインデックス リストを設定する必要があります。

((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 パーサーの例

  1. JTableにJavaで空のセルがあるかどうかを検証するにはどうすればよいですか?

    JTable JComponentのサブクラスです 複雑なデータ構造を表示するためのクラス。 JTableは、 Model View Controller(MVC)に従うことができます 行と列にデータを表示するためのデザインパターン 。 JTable TableModelListener、TableColumnModelListener、ListSelectionListener、CellEditorListenerを生成します およびRowSorterListener インターフェイス。 getValueAt()を実装することで、JTableセルが空かどうかを検証できます。

  2. JavaでJTreeのリーフを無効にするにはどうすればよいですか?

    JTree 階層を提示するコンポーネントです データの表示。ユーザーは拡張することができます または崩壊 個々のサブツリー。 TreeNode インターフェイスは、 JTreeのノードに実装する必要があるメソッドを定義します 物体。 DefaulMutableTreeNode クラスは、 TreeNodeのデフォルトの実装を提供します インターフェース。 getTreeCellRendererComponent()をオーバーライドすることで、JTreeのリーフを無効にできます。 Dの方法 efaultTreeCellRenderer クラス。 構文 public Compon