< 이전 | 다음 >

학습 2: EGL의 기본 SQL 조작

EGL 소개(빠른 시작 안내서)를 완료하면 관계형 데이터베이스에 액세스하는 데 필요한 EGL 파트와 데이터베이스에서 데이터를 읽고 쓰는 데 사용할 수 있는 명령을 배우게 됩니다. 이 학습에서 해당 개념을 보다 자세히 다룹니다.

이전 학습에서나 지난 학습서에서 데이터 액세스 응용프로그램 마법사를 실행한 경우 EGL이 데이터베이스의 정보를 기반으로 데이터 파트와 논리 파트를 작성합니다.

작성된 가장 중요한 데이터 파트는 SQLRecord 파트입니다. 이 레코드 파트의 필드는 데이터베이스의 열과 관련됩니다. 이 레코드를 기반으로 변수를 작성하면 해당 변수를 사용하여 데이터베이스에 신규 또는 기존 행을 나타낼 수 있습니다. 데이터 액세스 응용프로그램 마법사가 작성한 각 SQLRecord는 단일 테이블의 열과만 일치하지만 나중에 이 학습서에서 두 테이블 이상의 데이터를 단일 레코드로 병합하는 방법에 대해 설명할 것입니다(SQL에서는 테이블 결합이라고 함).

예를 들어, 이 학습서에서는 Customer SQLRecord를 사용할 것입니다. EGLSource/eglderbyr7/data/customer.egl 파일에서 이 레코드를 찾을 수 있습니다.
record Customer type sqlRecord { 
  tablenames=[["EGL.CUSTOMER"]],
  keyItems=[CustomerId]
  } 

  CustomerId CustomerId {column="EGL.CUSTOMER.CUSTOMER_ID"};
  FirstName FirstName {column="EGL.CUSTOMER.FIRST_NAME", 
    sqlVariableLen=yes, maxLen=30, isSqlNullable=yes};
  LastName LastName {column="EGL.CUSTOMER.LAST_NAME", 
    sqlVariableLen=yes, maxLen=30, isSqlNullable=yes};
...
  Directions Directions {column="EGL.CUSTOMER.DIRECTIONS", 
    sqlVariableLen=yes, maxLen=255, isSqlNullable=yes};
end
tablenames=[["EGL.CUSTOMER"]] 코드는 이 레코드가 연관된 데이터베이스의 테이블을 지정하며 각 필드의 특성은 필드가 연관된 테이블의 열을 지정합니다. keyItems=[CustomerId] 코드는 CustomerId 필드와 데이터베이스의 EGL.CUSTOMER.CUSTOMER_ID 열(CustomerId와의 연결로 인해)이 이 테이블의 1차 키임을 나타냅니다.
데이터 액세스 응용프로그램 마법사는 레코드 배열과 레코드에서 CRUD(Create, Read, Update 및 Delete) 조작을 수행하는 여러 라이브러리도 작성합니다. 이 라이브러리는 EGL 명령을 사용하여 CRUD 조작을 직접 수행하는 고급 방법입니다. 이 학습서에서는 EGL 명령을 직접 사용합니다. 그러나, 재사용을 위해 로직을 라이브러리로 구분하는 것이 편리합니다. 네 가지 EGL CRUD 명령은 다음과 같습니다.
표 1. EGL CRUD 명령 및 대응하는 SQL 명령
EGL 명령 EGL 예제 SQL 명령
add
add myRecord;
INSERT
get
get myRecord;
SELECT
replace
replace myRecord;
UPDATE
delete
delete myRecord;
DELETE
이 명령 중 하나를 사용하면 EGL이 해당 명령에서 기본 SQL 문을 생성합니다. 예를 들어, 다음 add 문이 있습니다.
add myCustomer;
myCustomer 레코드에 커서를 두고 마우스 오른쪽 단추를 클릭한 다음 SQL 문 > 추가를 클릭하면 EGL 편집기가 add 문을 펼쳐 SQL 코드를 표시하며 SQL 코드가 명시적으로 표시됩니다.
SQL 문이 명시적으로 표시되도록 하는 방법을 표시하는
컨텍스트 메뉴
add myCustomer with
  #sql{
    insert into EGL.CUSTOMER
      (EGL.CUSTOMER.CUSTOMER_ID, EGL.CUSTOMER.FIRST_NAME, 
      EGL.CUSTOMER.LAST_NAME, EGL.CUSTOMER.PASSWORD, 
      EGL.CUSTOMER.PHONE, EGL.CUSTOMER.EMAIL_ADDRESS, 
      EGL.CUSTOMER.STREET, EGL.CUSTOMER.APARTMENT, 
      EGL.CUSTOMER.CITY, EGL.CUSTOMER."STATE", 
      EGL.CUSTOMER.POSTALCODE, EGL.CUSTOMER.DIRECTIONS)
    values
      (:myCustomer.CustomerId, :myCustomer.FirstName, 
      :myCustomer.LastName, :myCustomer.Password, 
      :myCustomer.Phone, :myCustomer.EmailAddress, 
      :myCustomer.Street, :myCustomer.Apartment, 
      :myCustomer.City, :myCustomer.State, 
      :myCustomer.Postalcode, :myCustomer.Directions)
  };
내용은 변경되지 않습니다. EGL이 add 문에서 생성한 SQL 코드를 드러냈을 뿐입니다. 이제, 코드가 명시적이므로 EGL 명령에서 생성된 기본 SQL을 편집할 수 있습니다.

SQL INSERT 문의 VALUES절은 새 데이터베이스 행(이 경우, myCustomer 레코드의 필드)에 삽입할 값을 나열합니다. #sql 블록의 각 값 앞에는 콜론(:)이 오는데, 이는 값이 SQL 값이 아니라 EGL 값임을 나타냅니다. 명시적 SQL 코드에 사용하는 이 EGL 값은 호스트 변수라고 합니다.

작동하는 호스트 변수의 또 다른 예로서, 다음은 get 문을 사용하여 데이터베이스에서 일련의 레코드를 제거하는 함수입니다.
function getCustFromState(customerState CHAR(2) in, 
  customers Customer[] out)

  get customers with
    #sql{
      select *
      from EGL.CUSTOMER
      where EGL.CUSTOMER."STATE" like :customerState
    };

end
이 함수는 2바이트 CHAR 매개변수를 받은 다음 해당 매개변수를 호스트 변수로 사용하여 해당 두 문자에 일치하는 STATE 필드가 있는 레코드를 검색합니다. EGL이 명시적 SQL 코드와 작동할 수 있도록 하려면 호스트 변수를 주의하여 사용하십시오.

CRUD 조작 검토

이 절에서는 get, add, replacedelete를 사용하여 EGL로 기본 데이터베이스 조작을 수행합니다. 이 절은 선택사항입니다. 네 개의 기본 EGL 데이터 액세스 명령문 및 해당 SQL 대응 명령에 익숙하다면 이 절을 건너뛰십시오.

  1. 다음과 같이 CRUDTest.egl이라는 새 EGL 프로그램을 작성하십시오.
    1. 프로젝트 탐색기 보기에서 EGLSQL 프로젝트를 마우스 오른쪽 단추로 클릭한 다음 새로 작성 > 프로그램을 클릭하십시오. 새 EGL 프로그램 파트 창이 열립니다.
    2. 패키지 필드에 programs라는 이름을 입력하십시오.
    3. EGL 소스 파일 이름 필드에 CRUDTest라는 이름을 입력하십시오.
    4. 완료를 클릭하십시오.
    새 EGL 프로그램이 작성되어 편집기에서 열립니다.
  2. 기본 EGL 코드를 다음 코드로 바꾸십시오.
    package programs;
    
    import eglderbyr7.data.*;
    
    program CRUDTest type BasicProgram {}
      
      function main()
        
        try
          // Print the starting records in the database.
          SysLib.writeStdout("Contents of database before any SQL operations:");
          printAllCustomers();
          
        // What to do if an error happens.
        onException (exception SQLException)
          handleDBException(exception);
        end
        
      end
      
      // This function prints out the contents of the CUSTOMER
      // table in the database.
      function printAllCustomers()
        
        allCustomers Customer[0];
    
        get allCustomers;
        for (counter int from 1 to allcustomers.getSize())
          SysLib.writeStdout(allCustomers[counter].CustomerId::" "::
            allCustomers[counter].FirstName::" "::
            allCustomers[counter].LastName);
        end
        SysLib.writeStdout("\n");
    
      end
      
      //This function responds to errors accessing the database.
      function handleDBException(exception SQLException)
        SysLib.writeStdout("Error accessing database. "::
          "See Troubleshooting section");
        SysLib.writeStdout(exception.message);
      end
      
    end

    현재, 이 프로그램은 데이터베이스의 전체 고객 목록을 인쇄할 뿐입니다. 여기에는 handleDBException이라는 함수가 포함되어 데이터베이스와 작업할 때 EGL에서 발생하는 모든 문제점을 처리합니다(나중에 이 학습서에서 오류 처리에 대해 자세히 설명함). 이 프로그램을 지금 실행하여 변경 전의 데이터베이스 상태를 확인할 수 있습니다.

  3. 프로그램을 저장하고 생성하십시오.
  4. 다음과 같이 프로그램을 실행하십시오.
    1. 프로젝트 탐색기 보기에서 EGLSQL/JavaSource/programs를 펼치십시오.
    2. CRUDTest.java 파일을 마우스 오른쪽 단추로 클릭한 다음 실행 도구 > Java 응용프로그램을 클릭하십시오.
    오류 없이 프로그램이 실행되면 콘솔 보기가 데이터베이스의 컨텐츠를 표시합니다. 콘솔 보기의 결과는 다음과 유사합니다.
    Contents of database before any SQL operations:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
    콘솔 결과에 오류가 포함된 경우 프로그램을 정확하게 복사했는지 확인한 후 문제점 해결을 확인하십시오.
  5. 다음과 같이 마지막 end 문 앞에 데이터베이스에 새 행을 삽입하는 함수를 추가하십시오.
    function addCustomer()
      customerToAdd Customer;
      customerToAdd.CustomerId = 50;
      customerToAdd.FirstName = "John";
      customerToAdd.LastName = "Doe";
      
      // Insert the record into the database
      try
        add customerToAdd;
        SysLib.writeStdout("Contents of database after adding a new record:");
        printAllCustomers();
      onException(exception SQLException)
        handleDBException(exception);
      end
      
    end
    이 함수는 add를 사용하여 레코드를 데이터베이스에 삽입합니다. add문 뒤의 내재적 SQL 코드를 보려면 커서를 add customerToAdd; 행의 customerToAdd 키워드에 직접 두고 마우스 오른쪽 단추로 클릭한 다음 SQL 문 > 추가를 클릭하십시오. 이제, 명령문은 다음과 같습니다.
    try
      add customerToAdd with
        #sql{
          insert into EGL.CUSTOMER
            (EGL.CUSTOMER.CUSTOMER_ID, EGL.CUSTOMER.FIRST_NAME, 
            EGL.CUSTOMER.LAST_NAME, EGL.CUSTOMER.PASSWORD, 
            EGL.CUSTOMER.PHONE, EGL.CUSTOMER.EMAIL_ADDRESS, 
            EGL.CUSTOMER.STREET, EGL.CUSTOMER.APARTMENT, 
            EGL.CUSTOMER.CITY, EGL.CUSTOMER."STATE", 
            EGL.CUSTOMER.POSTALCODE, EGL.CUSTOMER.DIRECTIONS)
          values
            (:customerToAdd.CustomerId, :customerToAdd.FirstName, 
            :customerToAdd.LastName, :customerToAdd.Password, 
            :customerToAdd.Phone, :customerToAdd.EmailAddress, 
            :customerToAdd.Street, :customerToAdd.Apartment, 
            :customerToAdd.City, :customerToAdd.State, 
            :customerToAdd.Postalcode, :customerToAdd.Directions)
        };
    레코드 변수에 직접 커서를 두고 마우스 오른쪽 단추를 클릭한 다음 SQL 문 > 보기를 클릭하여 SQL 코드를 명시적으로 만들지 않은 상태에서 해당 코드를 미리볼 수도 있습니다. 이와 같이 EGL 코드에서 SQL 코드에 대한 작업을 수행하려면 EGL 편집기의 커서가 명령문에 있어야 합니다.
  6. 다음과 같이 프로그램의 main() 함수에서 새 함수를 호출하십시오.
    function main()
      
      // Print the starting records in the database.
      SysLib.writeStdout("Contents of database before any SQL operations:");
      printAllCustomers();
      
      // Add a record.
      addCustomer();
      
    end
  7. 프로그램을 저장하고 생성하여 실행하십시오. 다음 출력은 테이블에 레코드를 추가하기 전/후 테이블에 표시되는 컨텐츠입니다.
    Contents of database before any SQL operations:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
    
    
    Contents of database after adding a new record:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
    50 John Doe
  8. 데이터베이스에서 레코드를 삭제하는 함수를 다음과 같이 마지막 end 문 앞에 추가하십시오.
    function deleteCustomer()
      customerToDelete Customer;
      customerToDelete.CustomerId = 50;
      
      // Delete the record.
      try
        delete customerToDelete noCursor;
        SysLib.writeStdout("Contents of database after deleting the record:");
        printAllCustomers();
      onException(exception SQLException)
        handleDBException(exception);
      end
      
    end
  9. main() 함수에서 레코드를 추가하는 함수 호출을 레코드를 삭제하는 함수 호출로 바꾸십시오. CUSTOMER_ID 열은 테이블의 1차 키이며 테이블에 이미 CUSTOMER_ID가 50으로 설정된 행이 있으므로 레코드를 다시 추가하려고 하면 오류가 발생합니다.
    function main()
      
      // Print the starting records in the database.
      SysLib.writeStdout("Contents of database before any SQL operations:");
      printAllCustomers();
      
      // Delete a record.
      deleteCustomer();
      
    end
  10. 프로그램을 저장하고 생성하여 실행하십시오. 다음 출력은 테이블에서 레코드를 삭제하기 전/후 테이블에 표시되는 컨텐츠입니다.
    Contents of database before any SQL operations:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
    50 John Doe
    
    
    Contents of database after deleting the record:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
  11. 데이터베이스에서 레코드를 검색하고 갱신하는 함수를 다음과 같이 마지막 end 문 앞에 추가하십시오.
    function updateCustomer()
      customerToUpdate Customer;
      customerToUpdate.CustomerId = 50;
      
      // Retrieve the row.
      get customerToUpdate;
      
      // Change values in the record variable.
      customerToUpdate.FirstName = "Johnny";
      customerToUpdate.LastName = "Five";
      
      // Update the row in the database.
      try
        replace customerToUpdate noCursor;
        SysLib.writeStdout("Contents of database after updating the record:");
        printAllCustomers();
      onException(exception SQLException)
        handleDBException(exception);
      end
      
    end
  12. 프로그램의 main() 함수에서 추가, 바꾸기 및 삭제 함수를 순서대로 호출하십시오.
    function main()
      
      // Print the starting records in the database.
      SysLib.writeStdout("Contents of database before any SQL operations:");
      printAllCustomers();
      
      // Add a record.
      addCustomer();
      
      // Update the record.
      updateCustomer();
      
      // Delete a record.
      deleteCustomer();
      
    end
  13. 프로그램을 저장하고 생성하여 실행하십시오. 다음 각각의 출력은 레코드를 추가 후, 갱신 후 및 삭제한 후 프로그램의 시작에 표시되는 테이블 컨텐츠입니다.
    Contents of database before any SQL operations:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
    
    
    Contents of database after adding a new record:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
    50 John Doe
    
    
    Contents of database after updating the record:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
    50 Johnny Five
    
    
    Contents of database after deleting the record:
    1 Fred Filibuster
    2 Andy Lundquist
    3 Billie Kingman
    4 Francine Liebowitz
    5 Ornette Coleman
    6 Ellen Springsteen
    7 Martin St. Louis
    8 Sergey Sharov
    9 Melodie Hudak
CRUDTest.egl 파일의 전체 코드가 완성되었습니다. 파일에 빨간색 X 기호로 표시된 오류가 나타나면 코드가 학습 2에서 완성된 CRUDTest.egl 파일의 코드와 일치하는지 확인하십시오.

학습 체크포인트

이 학습에서는 EGL 및 SQL을 사용하여 관계형 데이터베이스에 액세스하는 기초적인 방법을 배웠습니다.

또한, 다음 개념도 이해하게 되었을 것입니다.
  • SQLRecord 파트 및 데이터베이스 테이블과의 해당 관계
  • 데이터베이스 조작을 수행하는 네 개의 기본 EGL 문
  • 명시적 SQL
  • 호스트 변수
네 가지 기본 EGL 데이터 액세스 명령문에 대한 자세한 정보는 다음 도움말 항목을 참조하십시오.
< 이전 | 다음 >