!--a11y-->
Accessing DataSourceUse this procedure to look up a DataSource. By performing a lookup operation, you obtain access to the DataSource object and can request a database connection from it.
To do this, you must:
· Look up the DataSource in the application code
· Add a resource reference in the deployment descriptor of the application component
...
The following steps describe the code that you have to include in your application component to look up the DataSource:
1. Get new initial context.

try { context = new InitialContext(); } catch (NamingException ne) { return; } |
2. Look up the DataSource.

DataSource ds = (DataSource) context.lookup("java:comp/env/<res-ref-name>") |
To look up and use a DataSource from your application components, you must add a resource reference to the DataSource in the standard deployment descriptor of the component – that is, web.xml for Web components, or ejb-jar.xmlfor enterprise beans.
Using resource references has several purposes:
· Resource references are defined by the J2EE standard. Using them makes your applications portable.
· By specifying a resource reference, you can access resources on the SAP J2EE Engine such as DataSource objects or other types of connection factories, even if they are not deployed with your application.
·
Declaring resource references enables you to manage
the use of other features, such as
connection
sharing.
To add a resource reference for a Web component in the SAP NetWeaver Developer Studio:
...
1. In the J2EE Development perspective, expand the relevant Web Module Project and open web.xml.
2. Go to the Resource tab. Select Resource entries and choose Add.
3. Edit the properties of the new resource reference as follows:


The resource reference name may be:
· The proper name of the DataSource – this is the name that you specify when you create the DataSource. For example, myDataSource.
·
An alias that you have set for this DataSource. For
information, see
Managing
Aliases.
·
An arbitrary name – in this case, you must
specify the JNDI name of the DataSource in the additional deployment
descriptor (
web-j2ee-engine.xml). To do that, open the
descriptor, go to the References tab, and add a resource-ref. The JNDI name of the DataSource is either its
proper name, or an alias.
4. Save and close web.xml.
To add a resource reference for an enterprise bean:
...
1. In the J2EE Development perspective, expand the relevant EJB Module Project and open ejb-jar.xml.
2. Go to the Enterprise Beans tab and browse to the node of the relevant bean and expand it.
3. Select resource-ref. Choose Add and edit the reference as described in step 3 above.

If
you choose to use an arbitrary name for the reference, you should specify the
JNDI name of the DataSource in the additional deployment descriptor (
ejb-j2ee-engine.xml).
4. Save and close ejb-jar.xml.
If the lookup operation finishes successfully, you can request a connection:

Connection conn = ds.getConnection(); |
