Java Reference
In-Depth Information
Using the DataSource Class
The javax.sql.DataSource class can also be used to establish a connection to a
database. A naming service is used to locate the database, meaning that the
database needs to bind its data source name with the naming service. This step
is typically not done by the programmer, but instead is accomplished using a
tool provided by the naming service, application server, or database vendor.
When using drivers and the DriverManager class, the URL for a data source
looks similar to:
jdbc: <protocol>:<data_source_name>
When using a naming service and the DataSource class, the URL for a data
source looks similar to:
jdbc/ <context>/<data_source_name>
For example, the following URL might be used to represent our movies
database:
jdbc/moviesDSN
Binding the Data Source Name
The DataSourceDemo program will not run on your computer unless you bind the data
source name in a naming service and then specify the naming service as a property when
running the program using the java.naming.factory.initial property.
For example, the following command line runs the DataSourceDemo program using the
rmiregistry as its naming service. (The rmiregistry comes with the J2SE SDK):
java -Djava.naming.factory.initial=
com.sun.jndi.rmi.registry.RegistryContextFactory
DataSourceDemo jdbc/moviesDSN
This still does not fix the problem of running this program on your computer, however,
because jdbc/moviesDSN is not a bound data source name in the rmiregistry. This is the
problem you will run into when using DataSource in a standalone application: You need a
naming service as well as a way to bind your database's data source name into the nam-
ing service. The J2SE API does not provide the classes for you to do this on your own. You
need to use third-party software.
So, why did I show you the DataSource technique for connecting to a database?
Because it is the preferred way to connect to a database, even though in standalone Java
applications such as the ones in this topic, you will probably use the DriverManager class.
You will most often see the DataSource class used in J2EE applications. That being said, I
wouldn't feel too bad about choosing DriverManager instead of the preferred DataSource
class for establishing database connections, especially because DriverManager has been
the only way to connect to a database for the first 5 years of Java database programming!
Search WWH ::




Custom Search