Example: Embed SQL Statements in your Java application

The following example SQLJ application, App.sqlj, uses static SQL to retrieve and update data from the EMPLOYEE table of the DB2® sample database.

Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
import java.sql.*;
import sqlj.runtime.*;
import sqlj.runtime.ref.*;

#sql iterator App_Cursor1 (String empno, String firstnme) ; // 1
#sql iterator App_Cursor2 (String) ;

class App
{

  /**********************
   **  Register Driver **
   **********************/

 static
 {
   try
   {
     Class.forName("com.ibm.db2.jdbc.app.DB2Driver").newInstance();
   }
   catch (Exception e)
   {
     e.printStackTrace();
   }
 }

  /********************
   **      Main      **
   ********************/

 public static void main(String argv[])
 {
   try
   {
     App_Cursor1 cursor1;
     App_Cursor2 cursor2;

     String str1 = null;
     String str2 = null;
     long   count1;

     // URL is jdbc:db2:dbname
     String url = "jdbc:db2:sample";

     DefaultContext ctx = DefaultContext.getDefaultContext();
     if (ctx == null)
     {
       try
       {
         // connect with default id/password
         Connection con = DriverManager.getConnection(url);
         con.setAutoCommit(false);
         ctx = new DefaultContext(con);
       }
       catch (SQLException e)
       {
         System.out.println("Error: could not get a default context");
         System.err.println(e) ;
         System.exit(1);
       }
       DefaultContext.setDefaultContext(ctx);
     }

     // retrieve data from the database
     System.out.println("Retrieve some data from the database.");
     #sql cursor1 = {SELECT empno, firstnme FROM employee}; // 2

     // display the result set
     // cursor1.next() returns false when there are no more rows
     System.out.println("Received results:");
     while (cursor1.next()) // 3
     {
       str1 = cursor1.empno(); // 4
       str2 = cursor1.firstnme();

       System.out.print (" empno= " + str1);
       System.out.print (" firstname= " + str2);
       System.out.println("");
     }
     cursor1.close(); // 9

     // retrieve number of employee from the database
     #sql { SELECT count(*) into :count1 FROM employee }; // 5
     if (1 == count1)
       System.out.println ("There is 1 row in employee table");
     else
       System.out.println ("There are " + count1
                            + " rows in employee table");

     // update the database
     System.out.println("Update the database.");
     #sql { UPDATE employee SET firstnme = 'SHILI' WHERE empno = '000010' };

     // retrieve the updated data from the database
     System.out.println("Retrieve the updated data from the database.");
     str1 = "000010";
     #sql cursor2 = {SELECT firstnme FROM employee WHERE empno = :str1}; // 6

     // display the result set
     // cursor2.next() returns false when there are no more rows
     System.out.println("Received results:");
     while (true)
     {
       #sql { FETCH :cursor2 INTO :str2 }; // 7
       if (cursor2.endFetch()) break; // 8

       System.out.print (" empno= " + str1);
       System.out.print (" firstname= " + str2);
       System.out.println("");
     }
     cursor2.close(); // 9

     // rollback the update
     System.out.println("Rollback the update.");
     #sql { ROLLBACK work };
     System.out.println("Rollback done.");
   }
   catch( Exception e )
   {
     e.printStackTrace();
   }
 }
}
1Declare iterators. This section declares two types of iterators:
  • App_Cursor1: Declares column data types and names, and returns the values of the columns according to column name (Named binding to columns).
  • App_Cursor2: Declares column data types, and returns the values of the columns by column position (Positional binding to columns).

2Initialize the iterator. The iterator object cursor1 is initialized using the result of a query. The query stores the result in cursor1.

3Advance the iterator to the next row. The cursor1.next() method returns a Boolean false if there are no more rows to retrieve.

4Move the data. The named accessor method empno() returns the value of the column named empno on the current row. The named accessor method firstnme() returns the value of the column named firstnme on the current row.

5SELECT data into a host variable. The SELECT statement passes the number of rows in the table into the host variable count1.

6 Initialize the iterator. The iterator object cursor2 is initialized using the result of a query. The query stores the result in cursor2.

7Retrieve the data. The FETCH statement returns the current value of the first column declared in the ByPos cursor from the result table into the host variable str2.

8Check the success of a FETCH.INTO statement. The endFetch() method returns a Boolean true if the iterator is not positioned on a row, that is, if the last attempt to fetch a row failed. The endFetch() method returns false if the last attempt to fetch a row was successful. DB2 attempts to fetch a row when the next() method is called. A FETCH...INTO statement implicitly calls the next() method.

9Close the iterators. The close() method releases any resources held by the iterators. You should explicitly close iterators to ensure that system resources are released in a timely fashion.

For background information on this example, see Embed SQL Statements in your Java™ application.

Related concepts
Example: IBM i5/OS PASE native method for Java
Related tasks
Example: Run the Java Performance Data Converter
Related reference
Example: Internationalization of dates using the java.util.DateFormat class
Example: Internationalization of numeric display using the java.util.NumberFormat class
Example: Internationalization of locale-specific data using the java.util.ResourceBundle class
Example: Access property
Example: BLOB
Example: CallableStatement interface for IBM Developer Kit for Java
Example: Remove values from a table through another statement's cursor
Example: CLOB
Example: Create a UDBDataSource and bind it with JNDI
Example: Create a UDBDataSource, and obtain a user ID and password
Example: Create a UDBDataSourceBind and set DataSource properties
Example: DatabaseMetaData interface for IBM Developer Kit for Java - Return a list of tables
Example: Datalink
Example: Distinct types
Example: End a transaction
Example: Invalid user ID and password
Example: JDBC
Example: Multiple connections that work on a transaction
Example: Obtain an initial context before binding UDBDataSource
Example: ParameterMetaData
Example: Change values with a statement through another statement's cursor
Example: ResultSet interface for IBM Developer Kit for Java
Example: ResultSet sensitivity
Example: Sensitive and insensitive ResultSets
Example: Set up connection pooling with UDBDataSource and UDBConnectionPoolDataSource
Example: SQLException
Example: Suspend and resume a transaction
Example: Suspended ResultSets
Example: Test the performance of connection pooling
Example: Test the performance of two DataSources
Example: Update BLOBs
Example: Update CLOBs
Example: Use a connection with multiple transactions
Example: Use BLOBs
Example: Use CLOBs
Example: Use JTA to handle a transaction
Example: Use metadata ResultSets that have more than one column
Example: Use native JDBC and IBM Toolbox for Java JDBC concurrently
Example: Use PreparedStatement to obtain a ResultSet
Create and populate a DB2CachedRowSet
Example: Use the Statement object's executeUpdate method
Examples: JAAS HelloWorld
Example: JAAS SampleThreadSubjectLogin
Sample: IBM JGSS non-JAAS client program
Sample: IBM JGSS non-JAAS server program
Sample: IBM JGSS JAAS-enabled client program
Sample: IBM JGSS JAAS-enabled server program
Examples: IBM Java Secure Sockets Extension
Example: Call a CL program with java.lang.Runtime.exec()
Example: Call a CL command with java.lang.Runtime.exec()
Example: Call another Java program with java.lang.Runtime.exec()
Example: Call Java from C
Example: Call Java from RPG
Example: Use input and output streams for interprocess communication
Example: Java Invocation API
Examples: Use the Java Native Interface for native methods
Example: Use sockets for interprocess communication
Example: Embed SQL Statements in your Java application
Examples: Change your Java code to use client socket factories
Examples: Change your Java code to use server socket factories
Examples: Change your Java client to use secure sockets layer
Examples: Change your Java server to use secure sockets layer