IBM DB2 Manual page 132

Table of Contents

Advertisement

import sqlj.runtime.*;
import java.sql.*;
import java.math.*;
import UpdByPos;
#sql context HSCtx;
public static void main (String args[])
{
}
Figure 33. Example of performing a positioned UPDATE with a positioned iterator
The following code shows how to declare a named iterator and use it for
positioned UPDATEs. The numbers to the right of selected statements correspond
to the previously described steps.
First, in one file, declare named iterator UpdByName, specifying that you want to use
the iterator to update column SALARY:
import java.math.*;
#sql public iterator UpdByName implements sqlj.runtime.ForUpdate
Figure 34. Example of declaring a named iterator for a positioned UPDATE
116
Application Programming Guide and Reference for Java
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection HSjdbccon=
DriverManager.getConnection("jdbc:db2:SANJOSE");
// Create a JDBC connection object
HSjdbccon.setAutoCommit(false);
// Set autocommit off so automatic commits
// do not destroy the cursor between updates
HSCtx myConnCtx=new HSCtx(HSjdbccon);
// Create a connection context object
UpdByPos upditer; // Declare iterator object of UpdByPos class
String empnum;
// Declares host variable to receive EMPNO
BigDecimal sal;
// and SALARY column values
#sql [myConnCtx]
upditer = {SELECT EMPNO, SALARY FROM EMPLOYEE
WHERE WORKDEPT='D11'};
// Assign result table to iterator object
#sql {FETCH :upditer INTO :empnum,:sal};
while (!upditer.endFetch())
{
#sql [myConnCtx] {UPDATE EMPLOYEE SET SALARY=SALARY*1.05
WHERE CURRENT OF :upditer};
System.out.println("Updating row for " + empnum);
#sql {FETCH :upditer INTO :empnum,:sal};
}
upditer.close();
#sql [myConnCtx] {COMMIT};
myConnCtx.close();
with(updateColumns="SALARY") (String EmpNo, BigDecimal Salary);
// Import files for SQLJ and JDBC APIs
// Import this class for BigDecimal data type
// Import the generated iterator class that
// was created by the iterator declaration clause
// for UpdByName in another file
// Create a connnection context class HSCtx
// Move cursor to next row
// Check if on a row
// Perform positioned update
// Move cursor to next row
// Close the iterator
// Commit the changes
// Close the connection context
// Import this class for BigDecimal data type
2
3
4
5a
5b
5c
6
1

Hide quick links:

Advertisement

Table of Contents
loading

Table of Contents