27.10.2013 Views

Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird

Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird

Jaybird 2.1 JDBC driver Java Programmer's Manual - Firebird

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

then name-value pairs separated with “&”. Code in Illustration 2.6 is equivalent to<br />

the previous example.<br />

import java.sql.*;<br />

...<br />

Class.forName("org.firebirdsql.jdbc.FBDriver");<br />

Connection connection = DriverManager.getConnection(<br />

"jdbc:firebirdsql:localhost/3050:C:/employee.gdb" +<br />

"?encoding=UNICODE_FSS",<br />

"SYSDBA",<br />

"masterkey");<br />

Illustration 2.5: Example of specifying extended properties in <strong>JDBC</strong> URL.<br />

Obtaining a connection via javax.sql.DataSource<br />

<strong>JDBC</strong> 2.0 specification introduced a new mechanism to obtain database<br />

connection without requiring the application to know any specifics of the<br />

underlying <strong>JDBC</strong> <strong>driver</strong>. The application is required to know a logical name under<br />

which application can find an instance of the javax.sql.DataSource interface<br />

using <strong>Java</strong> Naming and Directory Interface (JNDI). This is a common way to<br />

obtain connections in web and application servers.<br />

In order to obtain a connection via DataSource object, you can use code showed<br />

on Illustration 2.6. This code assumes that you have correctly configured JNDI<br />

properties. For more information about configuring JNDI please refer to the<br />

documentation provided with your web or application server.<br />

package hello;<br />

import java.sql.*;<br />

import javax.sql.*;<br />

import javax.naming.*;<br />

public class HelloServerJNDI {<br />

}<br />

public static void main(String[] args) throws Exception {<br />

}<br />

InitialContext ctx = new InitialContext();<br />

DataSource ds = (DataSource)ctx.lookup("jdbc/SomeDB");<br />

Connection connection = ds.getConnection();<br />

try {<br />

// do something here...<br />

} finally {<br />

connection.close();<br />

}<br />

Illustration 2.6: Typical way to obtain <strong>JDBC</strong> connection via JNDI.<br />

Usually binding between the DataSource object and its JNDI name happens in<br />

the configuration of your web or application server. However under some<br />

circumstances (e.g. you are developing your own JNDI-enabled application<br />

server/framework) you have to do this yourself. You can use the code snippet for<br />

Chapter 2. Obtaining a connection 12

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!