Java Reference
In-Depth Information
7.3
Creating an ODBC Data Source
Before an ODBC-driven database can be accessed via a Java program, it is neces-
sary to register the database as an ODBC Data Source. Once this has been done, the
database can be referred to by its Data Source Name (DSN). Assuming that the
database has already been created, the steps required to set up your own ODBC
Data Source are shown below. (These instructions were used on a Windows 7
machine and the naming of some items may vary slightly with other MS operating
systems, but the basic steps should remain much the same.)
1. Select
start
Run…
2. Enter
cmd
and click on OK.
3. Enter
C:\windows\syswow64\odbcad32.exe
.
4. Ensure that the
User DSN
tab is selected .
5. Click on the
Add…
button to display the
Create New Data Source
window.
6. Select
Microsoft Access Driver (*.mdb, *.accdb)
and click on
Finish
.
7. To locate the required database within the directory structure, click on the
Select…
button.
8. Navigate through the directory structure and select your database.
9. Supply a name for the data source. ('Description' fi eld is optional.)
10. If specifying a username and password (not mandatory and not necessary for
the examples in this section), click on
Advanced Options
and key in the values,
clicking
OK
when fi nished.
11.
Click
OK
to fi nish registration.
→
N.B. Remember that the above procedure is required
only
for ODBC databases!
The next section describes how our Java code can make use of the database's
DSN to retrieve data from the database and is applicable to
any
type of relational
database.
7.4
Simple Database Access
In what follows, reference will be made to
Connection
,
Statement
and
ResultSet
objects. These three names actually refer to
interfaces
, rather than classes. Each
JDBC driver must implement these three interfaces and the implementation classes
may then be used to create objects that may conveniently be referred to as
Connection
,
Statement
and
ResultSet
objects respectively. Similar comments apply
to interfaces
ResultSetMetaData
and
DatabaseMetaData
in Sect.
7.7
. From now on,
such terminology will be used freely and this point will not be laboured any further.
Using JDBC 4 to access a database requires several steps, as described below.
1. Establish a connection to the database.
2. Use the connection to create a
Statement
object and store a reference to this object.
3. Use the above
Statement
reference to run a specifi c query or update statement
and accept the result(s).
Search WWH ::
Custom Search