Java Reference
In-Depth Information
4. Manipulate and display the results (if a query) or check/show number of database
rows affected (for an update).
5. Repeat steps 4 and 5 as many times as required for further queries/updates.
6. Close the connection.
[If using an earlier version of JDBC, the following additional step is required
before those above: Load the database driver. ]
For purposes of illustration, we shall assume the existence of an MS Access
database called Finances.accdb that holds a single table called Accounts . The structure
of this simple table is as shown below.
Field name
MS access type
Java type
fi rstNames
fl oat
We shall further assume that the DSN given to the database is Finances .
Let's take each of the above seven steps in turn for this database…
1. Establish a Connection to the Database
We declare a Connection reference and call static method getConnection of class
DriverManager to return a Connection object for this reference. Method get-
Connection takes three String arguments:
a URL-style address for the database;
a user name;
a password.
The JDBC API specifi cation recommends that the database address have the
following format:
Here, <sub-protocol> specifi es a database connection service (i.e., a
driver ) and <data-source> provides all the information needed by the service
to locate the database (typically, the URL path to the database). For a local ODBC
database with data source name Finances , the sub-protocol is odbc and the fi nal part
of the address is simply the name of the data source:
Assuming that our Finances database is indeed local and that we did not set a
user name or password for this database, the line required to open a connection to
the database would be similar to this:
Connection connection =
"jdbc:odbc:Finances", "", "");
Search WWH ::

Custom Search