The following code uses connection technique 3 to create a connection to a location
with logical name jdbc/sampledb. This example assumes that the system
administrator created and deployed a DataSource object that is available through
JNDI lookup. The numbers to the right of selected statements correspond to the
previously-described steps.
SQLJ connection technique 4: JDBC DataSource interface
SQLJ connection technique 4 uses the JDBC DataSource as the underlying means
for creating the connection. This technique requires that the DataSource is
registered with JNDI.
To use SQLJ connection technique 4, follow these steps:
1. From your system administrator, obtain the logical name of the data source to
which you need to connect.
2. Execute an SQLJ connection declaration clause.
For this type of connection, the connection declaration clause needs to be of
this form:
#sql public static context context-class-name
with (dataSource="logical-name");
The connection context must be declared as public and static. logical-name is the
data source name that you obtained in step 1.
3. Invoke the constructor for the connection context class that you created in step
2.
Doing this creates a connection context object that you specify in each SQL
statement that you execute at the associated data source. The constructor
invocation statement needs to be in one of the following forms:
connection-context-class connection-context-object=
new connection-context-class();
connection-context-class connection-context-object=
new connection-context-class (String user,
String password);
The meanings of the user and password parameters are:
user and password
Specify a user ID and password for connection to the data source, if the
data source to which you are connecting requires them.
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
...
#sql context CtxSqlj; // Create connection context class CtxSqlj 1
Context ctx=new InitialContext(); 2b
DataSource ds=(DataSource)ctx.lookup("jdbc/sampledb"); 2c
Connection con=ds.getConnection(); 3
String empname; // Declare a host variable
...
con.setAutoCommit(false); // Do not autocommit 4
CtxSqlj myConnCtx=new CtxSqlj(con); 5
// Create connection context object myConnCtx
#sql [myConnCtx] {SELECT LASTNAME INTO :empname FROM EMPLOYEE
WHERE EMPNO='000010'};
// Use myConnCtx for executing an SQL statement
Figure 30. Using connection technique 3 to connect to a data source
108 Application Programming Guide and Reference for Java
™